subagent-profile-scenario.ts 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. import { expect, vi } from "vitest";
  2. import {
  3. SessionEventType,
  4. createSessionId,
  5. type ModelRequest,
  6. type ModelResult,
  7. type SessionId,
  8. } from "@zcode/contracts";
  9. import type { AgentProfile } from "../src/subagent/profile.js";
  10. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  11. import { createTestSessionEventStore } from "./test-event-store.js";
  12. import { createTestModelFactory } from "./test-runtime-model.js";
  13. import { createRecordingSubagentSessionStore } from "./subagent-test-store.js";
  14. export const usage = { inputTokens: 1, outputTokens: 1, totalTokens: 2 };
  15. export const done = (): ModelResult => ({ finishReason: "stop", text: "done", usage });
  16. export const initial = (): AgentProfile => ({
  17. name: "reviewer",
  18. source: "user",
  19. description: "Review",
  20. tools: ["Read"],
  21. systemPrompt: "PROFILE_ORIGINAL",
  22. modelSelection: { providerId: "custom", modelId: "fixed", options: { reasoningLevel: "low" } },
  23. });
  24. export const spawn = (prompt: string, background = false) => ({
  25. id: `spawn_${prompt}`,
  26. name: "Agent",
  27. input: { description: prompt, prompt, subagent_type: "reviewer", run_in_background: background },
  28. });
  29. export const send = (id: string, message: string) => ({
  30. id: `send_${message}`,
  31. name: "SendMessage",
  32. input: { to: id, message, summary: message },
  33. });
  34. type Call = ReturnType<typeof spawn> | ReturnType<typeof send>;
  35. export interface ChildRequest {
  36. sessionId: SessionId;
  37. model: string;
  38. reasoning: unknown;
  39. request: ModelRequest;
  40. }
  41. export function setup(onChild?: (record: ChildRequest) => Promise<ModelResult>) {
  42. const sessionId = createSessionId();
  43. const store = createRecordingSubagentSessionStore();
  44. const events = createTestSessionEventStore();
  45. const children: ChildRequest[] = [];
  46. const parents: ModelRequest[] = [];
  47. let profile = initial();
  48. let calls: Call[] = [],
  49. marker = "",
  50. sequence = 0,
  51. issued = false;
  52. const load = vi.fn(async () => ({ activeAgents: [profile] }));
  53. const runtime = createTestAgentRuntime(
  54. sessionId,
  55. { mode: "yolo", compact: { enabled: false }, titleGeneration: { enabled: false } },
  56. {
  57. sessionStore: store,
  58. eventStore: events,
  59. loadAgentDefinitions: load,
  60. modelFactory: createTestModelFactory({
  61. async generateText(request, observation) {
  62. if (observation.invocationContext?.metadata?.querySource === "subagent") {
  63. const record: ChildRequest = {
  64. sessionId: observation.invocationContext.traceContext!.sessionId!,
  65. model: observation.model.modelId,
  66. reasoning: observation.model.options.reasoningLevel,
  67. request: structuredClone(request),
  68. };
  69. children.push(record);
  70. return onChild ? onChild(record) : done();
  71. }
  72. parents.push(structuredClone(request));
  73. if (!issued && JSON.stringify(request.messages).includes(marker)) {
  74. issued = true;
  75. return { finishReason: "tool-calls", text: "", usage, toolCalls: calls };
  76. }
  77. return done();
  78. },
  79. }),
  80. },
  81. );
  82. const lifecycle = async (type: SessionEventType) =>
  83. (await events.getEvents(sessionId))
  84. .filter((event) => event.type === type)
  85. .map(
  86. (event) => event.payload as { agentId: string; childSessionId: SessionId; status: string },
  87. );
  88. return {
  89. store,
  90. runtime,
  91. events,
  92. parents,
  93. children,
  94. load,
  95. update(next: AgentProfile) {
  96. profile = next;
  97. },
  98. async turn(next: Call[]) {
  99. calls = next;
  100. marker = `PROFILE_FIELDS_TURN_${++sequence}`;
  101. issued = false;
  102. await runtime.executeTurn(marker);
  103. expect(issued).toBe(true);
  104. },
  105. spawned: () => lifecycle(SessionEventType.SubagentSpawned),
  106. async waitCompleted(id: string, count: number) {
  107. await vi.waitFor(async () =>
  108. expect(
  109. (await lifecycle(SessionEventType.SubagentStopped)).filter(
  110. (event) => event.agentId === id && event.status === "completed",
  111. ),
  112. ).toHaveLength(count),
  113. );
  114. },
  115. };
  116. }
  117. export function assertProfile(record: ChildRequest, profile: AgentProfile) {
  118. expect(record.model).toBe(profile.modelSelection!.modelId);
  119. expect(record.reasoning).toBe(profile.modelSelection!.options!.reasoningLevel);
  120. const system = record.request.messages.filter((m) => m.role === "system");
  121. expect(JSON.stringify(system)).toContain(profile.systemPrompt);
  122. expect(record.request.tools?.map((tool) => tool.name)).toEqual([
  123. ...profile.tools!,
  124. "RespondToCoordinator",
  125. ]);
  126. }