runtime-hooks.test.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. HookEventName,
  4. RESPOND_TO_COORDINATOR_TOOL_NAME,
  5. SEND_MESSAGE_TOOL_NAME,
  6. SessionEventType,
  7. createSessionId,
  8. modelMessageContentToText,
  9. type ModelMessageContent,
  10. type CoordinatorResponsePort,
  11. type SubagentPort,
  12. type SubagentSendMessageRequest,
  13. } from "@zcode/contracts";
  14. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  15. import { createInMemoryHookRunner } from "../src/hooks/index.js";
  16. import { createTestSessionEventStore } from "./test-event-store.js";
  17. import { respondToCoordinatorToolEntry } from "../src/tool/handlers/respond-to-coordinator.js";
  18. import { createTestModelFactory } from "./test-runtime-model.js";
  19. import { createRuntimeCommandId } from "../src/runtime/command-queue.js";
  20. describe("AgentRuntime lifecycle hooks", () => {
  21. it("queues deferred input as TurnSteerQueued when no active turn is steerable", async () => {
  22. const sessionId = createSessionId("runtime-deferred-input");
  23. const eventStore = createTestSessionEventStore();
  24. const runtime = createTestAgentRuntime(sessionId, {}, { eventStore });
  25. const result = await runtime.enqueueDeferredInput({
  26. input: "验证期间追加",
  27. inputId: "cmd-deferred",
  28. });
  29. if (result.kind !== "queued") {
  30. throw new Error(`unexpected deferred input result: ${result.kind}`);
  31. }
  32. const events = await eventStore.getEvents(sessionId);
  33. const queued = events.find((event) => event.type === SessionEventType.TurnSteerQueued);
  34. expect(queued?.payload).toMatchObject({
  35. delivery: "queue",
  36. input: "验证期间追加",
  37. inputId: "cmd-deferred",
  38. pendingInputId: result.pendingInputId,
  39. targetTurnId: "deferred",
  40. });
  41. });
  42. it("accepts attachment-only deferred input and preserves canonical refs", async () => {
  43. const sessionId = createSessionId("runtime-deferred-attachment-only");
  44. const eventStore = createTestSessionEventStore();
  45. const runtime = createTestAgentRuntime(sessionId, {}, { eventStore });
  46. const attachmentRefs = [
  47. { ref: "artifact://note", fileName: "note.txt", mime: "text/plain", bytes: 9 },
  48. ];
  49. const result = await runtime.enqueueDeferredInput({
  50. input: "",
  51. inputId: "cmd-attachment-only",
  52. attachments: [
  53. {
  54. type: "file",
  55. content: "note body",
  56. path: "note.txt",
  57. filename: "note.txt",
  58. mimeType: "text/plain",
  59. sizeBytes: 9,
  60. },
  61. ],
  62. intent: {
  63. sourceCommandId: "cmd-attachment-only",
  64. clientId: "mobile-client",
  65. kind: "sendText",
  66. admissionSeq: 1,
  67. admittedAt: 1_234,
  68. requestedDelivery: "guide",
  69. admittedDelivery: "queue",
  70. attachmentRefs,
  71. },
  72. });
  73. expect(result.kind).toBe("queued");
  74. const queued = (await eventStore.getEvents(sessionId)).find(
  75. (event) => event.type === SessionEventType.TurnSteerQueued,
  76. );
  77. expect(queued?.payload).toMatchObject({
  78. input: "",
  79. inputId: "cmd-attachment-only",
  80. intent: { attachmentRefs },
  81. });
  82. });
  83. it("rejects deferred input only when both text and attachments are empty", async () => {
  84. const sessionId = createSessionId("runtime-deferred-empty-input");
  85. const eventStore = createTestSessionEventStore();
  86. const runtime = createTestAgentRuntime(sessionId, {}, { eventStore });
  87. const result = await runtime.enqueueDeferredInput({ input: " ", attachments: [] });
  88. expect(result).toMatchObject({ kind: "rejected", reason: "empty_input" });
  89. const events = await eventStore.getEvents(sessionId);
  90. expect(events.some((event) => event.type === SessionEventType.TurnSteerQueued)).toBe(false);
  91. });
  92. it("injects SessionStart once and UserPromptSubmit context before model requests", async () => {
  93. const sessionId = createSessionId("runtime-hooks-context");
  94. const eventStore = createTestSessionEventStore();
  95. const hookEvents: string[] = [];
  96. const sessionStartModels: string[] = [];
  97. const capturedRequests: string[] = [];
  98. const hookRunner = createInMemoryHookRunner({
  99. hooks: [
  100. {
  101. event: HookEventName.SessionStart,
  102. callback: async (input) => {
  103. hookEvents.push(`${input.hookEventName}:${input.source}`);
  104. sessionStartModels.push(input.model);
  105. return {
  106. hookSpecificOutput: {
  107. additionalContext: "session-start-context",
  108. hookEventName: HookEventName.SessionStart,
  109. },
  110. };
  111. },
  112. },
  113. {
  114. event: HookEventName.UserPromptSubmit,
  115. callback: async (input) => {
  116. hookEvents.push(`${input.hookEventName}:${input.prompt}`);
  117. return {
  118. hookSpecificOutput: {
  119. additionalContext: `prompt-context:${input.prompt}`,
  120. hookEventName: HookEventName.UserPromptSubmit,
  121. },
  122. };
  123. },
  124. },
  125. ],
  126. });
  127. const runtime = createTestAgentRuntime(
  128. sessionId,
  129. {},
  130. {
  131. eventStore,
  132. hookRunner,
  133. modelFactory: createTestModelFactory({
  134. async generateText(request: { messages: Array<{ content: ModelMessageContent }> }) {
  135. capturedRequests.push(
  136. request.messages
  137. .map((message) => modelMessageContentToText(message.content))
  138. .join("\n"),
  139. );
  140. return modelTextResult("ok");
  141. },
  142. } as never),
  143. },
  144. );
  145. await runtime.executeTurn("first", undefined, {
  146. intent: {
  147. kind: "sendText",
  148. modelSelection: {
  149. providerId: "provider-b",
  150. modelId: "model-b",
  151. options: { reasoningLevel: "high" },
  152. },
  153. requestedDelivery: "start-now",
  154. sourceCommandId: "hook-model-switch",
  155. },
  156. });
  157. await runtime.executeTurn("second");
  158. expect(hookEvents).toEqual([
  159. "SessionStart:startup",
  160. "UserPromptSubmit:first",
  161. "UserPromptSubmit:second",
  162. ]);
  163. expect(sessionStartModels).toEqual(["provider-b/model-b"]);
  164. expect(capturedRequests[0]).toContain("session-start-context");
  165. expect(capturedRequests[0]).toContain("prompt-context:first");
  166. expect(capturedRequests[1]).toContain("prompt-context:second");
  167. });
  168. // 会话工具设计 0.8:提醒指向 ReadSession,且只在注册了会话工具的根会话注入。
  169. it.each([true, false])(
  170. "injects a ReadSession reminder for a session id only with session tools (%s)",
  171. async (withSessionControl) => {
  172. const sessionId = createSessionId("runtime-session-reference");
  173. const referencedSessionId = createSessionId("referenced-context");
  174. const eventStore = createTestSessionEventStore();
  175. const capturedRequests: string[] = [];
  176. const runtime = createTestAgentRuntime(
  177. sessionId,
  178. {},
  179. {
  180. eventStore,
  181. ...(withSessionControl
  182. ? {
  183. sessionControl: {
  184. kind: "cli" as const,
  185. context: () => ({ rootSession: { kind: "cli", sessionId } }) as never,
  186. control: {} as never,
  187. },
  188. }
  189. : {}),
  190. modelFactory: createTestModelFactory({
  191. async generateText(request: { messages: Array<{ content: ModelMessageContent }> }) {
  192. capturedRequests.push(
  193. request.messages
  194. .map((message) => modelMessageContentToText(message.content))
  195. .join("\n"),
  196. );
  197. return modelTextResult("ok");
  198. },
  199. } as never),
  200. },
  201. );
  202. await runtime.executeTurn(`continue from #${referencedSessionId}`);
  203. expect(capturedRequests[0]).not.toContain("ReadSessionContext");
  204. if (withSessionControl) {
  205. expect(capturedRequests[0]).toContain("ReadSession with sessionId");
  206. expect(capturedRequests[0]).toContain(`- ${referencedSessionId}`);
  207. } else {
  208. expect(capturedRequests[0]).not.toContain("ReadSession with sessionId");
  209. }
  210. },
  211. );
  212. it("blocks UserPromptSubmit before calling the model", async () => {
  213. const sessionId = createSessionId("runtime-hooks-block-prompt");
  214. const eventStore = createTestSessionEventStore();
  215. let modelCalled = false;
  216. const hookRunner = createInMemoryHookRunner({
  217. emitEvent: async (event) => {
  218. await eventStore.append(event);
  219. },
  220. hooks: [
  221. {
  222. event: HookEventName.UserPromptSubmit,
  223. callback: async () => ({
  224. continue: false,
  225. reason: "blocked by prompt hook",
  226. hookSpecificOutput: {
  227. hookEventName: HookEventName.UserPromptSubmit,
  228. },
  229. }),
  230. },
  231. ],
  232. });
  233. const runtime = createTestAgentRuntime(
  234. sessionId,
  235. {},
  236. {
  237. eventStore,
  238. hookRunner,
  239. modelFactory: createTestModelFactory({
  240. async generateText() {
  241. modelCalled = true;
  242. return modelTextResult("should not run");
  243. },
  244. } as never),
  245. },
  246. );
  247. const result = await runtime.executeTurn("blocked prompt");
  248. const events = await eventStore.getEvents(sessionId);
  249. expect(result.response).toBe("blocked by prompt hook");
  250. expect(modelCalled).toBe(false);
  251. expect(events.map((event) => event.type)).toContain(SessionEventType.HookRunBlocked);
  252. expect(events.map((event) => event.type)).not.toContain(SessionEventType.ModelRequest);
  253. });
  254. it("uses Stop hook feedback to continue the model loop", async () => {
  255. const sessionId = createSessionId("runtime-hooks-stop-continue");
  256. const eventStore = createTestSessionEventStore();
  257. let modelCallCount = 0;
  258. const capturedRequests: string[] = [];
  259. const hookRunner = createInMemoryHookRunner({
  260. hooks: [
  261. {
  262. event: HookEventName.Stop,
  263. callback: async () => {
  264. if (modelCallCount > 1) return undefined;
  265. return {
  266. decision: "block",
  267. reason: "revise with the stop hook feedback",
  268. systemMessage: "Ralph iteration 2",
  269. };
  270. },
  271. },
  272. ],
  273. });
  274. const runtime = createTestAgentRuntime(
  275. sessionId,
  276. { outputStyle: { name: "Learning", prompt: "Explain tradeoffs while solving the task." } },
  277. {
  278. eventStore,
  279. hookRunner,
  280. modelFactory: createTestModelFactory({
  281. async generateText(request: { messages: Array<{ content: ModelMessageContent }> }) {
  282. modelCallCount++;
  283. capturedRequests.push(
  284. request.messages
  285. .map((message) => modelMessageContentToText(message.content))
  286. .join("\n"),
  287. );
  288. return modelTextResult(modelCallCount === 1 ? "draft answer" : "final answer");
  289. },
  290. } as never),
  291. },
  292. );
  293. const result = await runtime.executeTurn("write an answer");
  294. expect(result.response).toBe("final answer");
  295. expect(modelCallCount).toBe(2);
  296. expect(capturedRequests[1]).toContain("draft answer");
  297. expect(capturedRequests[1]).toContain("revise with the stop hook feedback");
  298. // Stop hook 续跑不是新的输入:不再收集输入附件,output_style 仍只有轮首那一条。
  299. expect(capturedRequests[1]!.match(/Learning output style is active/g)).toHaveLength(1);
  300. });
  301. it("leaves a notification queued during a Stop hook continuation", async () => {
  302. const sessionId = createSessionId("runtime-hooks-stop-no-notification-drain");
  303. let modelCallCount = 0;
  304. const capturedRequests: string[] = [];
  305. let internal:
  306. | {
  307. branchGeneration: number;
  308. enqueueRuntimeCommand(command: unknown): void;
  309. rootTraceContext: unknown;
  310. }
  311. | undefined;
  312. const hookRunner = createInMemoryHookRunner({
  313. hooks: [
  314. {
  315. event: HookEventName.Stop,
  316. callback: async () => {
  317. if (modelCallCount > 1) return undefined;
  318. internal!.enqueueRuntimeCommand({
  319. branchGeneration: internal!.branchGeneration,
  320. createdAt: new Date(),
  321. id: createRuntimeCommandId(),
  322. mode: "task-notification",
  323. priority: "next",
  324. source: "background_task",
  325. taskId: "bg-task",
  326. text: "<task-notification>background task done</task-notification>",
  327. traceContext: internal!.rootTraceContext,
  328. });
  329. return { decision: "block", reason: "revise" };
  330. },
  331. },
  332. ],
  333. });
  334. const runtime = createTestAgentRuntime(
  335. sessionId,
  336. {},
  337. {
  338. eventStore: createTestSessionEventStore(),
  339. hookRunner,
  340. modelFactory: createTestModelFactory({
  341. async generateText(request: { messages: Array<{ content: ModelMessageContent }> }) {
  342. modelCallCount++;
  343. capturedRequests.push(
  344. request.messages
  345. .map((message) => modelMessageContentToText(message.content))
  346. .join("\n"),
  347. );
  348. return modelTextResult(`answer ${modelCallCount}`);
  349. },
  350. } as never),
  351. },
  352. );
  353. internal = runtime as unknown as NonNullable<typeof internal>;
  354. await runtime.executeTurn("write an answer");
  355. await vi.waitFor(() => expect(modelCallCount).toBe(3));
  356. // 通知只在完整工具批次之后取出;Stop hook 续跑重发同一份输入,不插入通知。
  357. expect(capturedRequests[1]).not.toContain("background task done");
  358. // 通知留在队列里,本轮结束后开新一轮。
  359. expect(capturedRequests[2]).toContain("background task done");
  360. });
  361. it("caps consecutive Stop hook continuations at three", async () => {
  362. const sessionId = createSessionId("runtime-hooks-stop-cap");
  363. const eventStore = createTestSessionEventStore();
  364. let hookCallCount = 0;
  365. let modelCallCount = 0;
  366. const hookRunner = createInMemoryHookRunner({
  367. hooks: [
  368. {
  369. event: HookEventName.Stop,
  370. callback: async () => {
  371. hookCallCount++;
  372. return {
  373. decision: "block",
  374. reason: `stop feedback ${hookCallCount}`,
  375. };
  376. },
  377. },
  378. ],
  379. });
  380. const runtime = createTestAgentRuntime(
  381. sessionId,
  382. {},
  383. {
  384. eventStore,
  385. hookRunner,
  386. modelFactory: createTestModelFactory({
  387. async generateText() {
  388. modelCallCount++;
  389. return modelTextResult(`answer ${modelCallCount}`);
  390. },
  391. } as never),
  392. },
  393. );
  394. const result = await runtime.executeTurn("write an answer");
  395. expect(result.response).toBe("answer 4");
  396. expect(modelCallCount).toBe(4);
  397. expect(hookCallCount).toBe(4);
  398. });
  399. it("injects built-in session mailbox context when messaging is enabled", async () => {
  400. const sessionId = createSessionId("runtime-mailbox-hooks");
  401. const eventStore = createTestSessionEventStore();
  402. const capturedRequests: string[] = [];
  403. let drained = false;
  404. const runtime = createTestAgentRuntime(
  405. sessionId,
  406. {},
  407. {
  408. eventStore,
  409. sessionMailboxPort: {
  410. async drainUnread() {
  411. if (drained) return [];
  412. drained = true;
  413. return [
  414. {
  415. version: 1,
  416. messageId: "mail-1",
  417. fromSessionId: "source-session",
  418. toSessionId: sessionId,
  419. content: "please check the failing test",
  420. createdAt: new Date().toISOString(),
  421. },
  422. ];
  423. },
  424. },
  425. modelFactory: createTestModelFactory({
  426. async generateText(request: { messages: Array<{ content: ModelMessageContent }> }) {
  427. capturedRequests.push(
  428. request.messages
  429. .map((message) => modelMessageContentToText(message.content))
  430. .join("\n"),
  431. );
  432. return modelTextResult("ok");
  433. },
  434. } as never),
  435. },
  436. );
  437. await runtime.executeTurn("work");
  438. expect(capturedRequests[0]).toContain("<session-message");
  439. expect(capturedRequests[0]).toContain("mail-1");
  440. expect(capturedRequests[0]).toContain("please check the failing test");
  441. expect(runtime.getToolRegistry().has("send_message")).toBe(false);
  442. const sendMessageTool = runtime.getToolRegistry().get(SEND_MESSAGE_TOOL_NAME);
  443. if (!sendMessageTool) throw new Error("Expected send_message tool to be registered");
  444. const sendMessageInputProperties = (sendMessageTool.inputSchema as any).properties;
  445. expect(sendMessageInputProperties).toHaveProperty("to");
  446. expect(sendMessageInputProperties).toHaveProperty("summary");
  447. expect(sendMessageInputProperties).toHaveProperty("message");
  448. expect(sendMessageInputProperties).not.toHaveProperty("sessionId");
  449. expect(sendMessageInputProperties).not.toHaveProperty("content");
  450. });
  451. it("executes SendMessage to a local_agent through the subagent port", async () => {
  452. const sessionId = createSessionId("runtime-send-message-local-agent");
  453. const eventStore = createTestSessionEventStore();
  454. const sentMessages: SubagentSendMessageRequest[] = [];
  455. const capturedRequests: string[] = [];
  456. let modelCallCount = 0;
  457. const subagentPort: SubagentPort = {
  458. async launch() {
  459. throw new Error("Agent tool should not launch in this test");
  460. },
  461. async run() {
  462. throw new Error("Agent tool should not run in this test");
  463. },
  464. async sendMessage(input) {
  465. sentMessages.push(input);
  466. return {
  467. status: "success",
  468. messageId: "msg-local-agent-1",
  469. delivery: "steered",
  470. agentId: input.to,
  471. taskId: input.to,
  472. message: `Message msg-local-agent-1 (${input.summary}) sent to ${input.to}.`,
  473. };
  474. },
  475. };
  476. const runtime = createTestAgentRuntime(
  477. sessionId,
  478. {},
  479. {
  480. eventStore,
  481. subagentPort,
  482. modelFactory: createTestModelFactory({
  483. async generateText(request: { messages: Array<{ content: ModelMessageContent }> }) {
  484. modelCallCount++;
  485. capturedRequests.push(
  486. request.messages
  487. .map((message) => modelMessageContentToText(message.content))
  488. .join("\n"),
  489. );
  490. if (modelCallCount === 1) {
  491. return {
  492. finishReason: "tool-calls",
  493. model: "test",
  494. providerMetadata: undefined,
  495. text: "",
  496. toolCalls: [
  497. {
  498. id: "send-local-agent-call-1",
  499. input: {
  500. to: "agent_local_1",
  501. summary: "继续检查权限",
  502. message: "请继续检查权限链路,并只报告结论。",
  503. },
  504. name: SEND_MESSAGE_TOOL_NAME,
  505. },
  506. ],
  507. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  508. };
  509. }
  510. return modelTextResult("sent to local agent");
  511. },
  512. } as never),
  513. },
  514. );
  515. const result = await runtime.executeTurn("send the local agent follow-up");
  516. expect(result.response).toBe("sent to local agent");
  517. expect(modelCallCount).toBe(2);
  518. expect(sentMessages).toEqual([
  519. expect.objectContaining({
  520. message: "请继续检查权限链路,并只报告结论。",
  521. summary: "继续检查权限",
  522. to: "agent_local_1",
  523. }),
  524. ]);
  525. expect(capturedRequests[1]).toContain(
  526. "Message msg-local-agent-1 (继续检查权限) sent to agent_local_1.",
  527. );
  528. });
  529. it("executes RespondToCoordinator from a plan-mode child runtime", async () => {
  530. const sessionId = createSessionId("runtime-respond-to-coordinator-plan");
  531. const requests: Parameters<CoordinatorResponsePort["respond"]>[0][] = [];
  532. let modelCallCount = 0;
  533. const runtime = createTestAgentRuntime(
  534. sessionId,
  535. { mode: "plan", taskType: "subagent_child" },
  536. {
  537. coordinatorResponsePort: {
  538. respond(request) {
  539. requests.push(request);
  540. return {
  541. status: "success",
  542. responseId: "response_plan_1",
  543. message: "Response response_plan_1 was queued for the coordinator.",
  544. };
  545. },
  546. },
  547. eventStore: createTestSessionEventStore(),
  548. modelFactory: createTestModelFactory({
  549. async generateText() {
  550. modelCallCount++;
  551. if (modelCallCount === 1) {
  552. return {
  553. finishReason: "tool-calls",
  554. model: "test",
  555. providerMetadata: undefined,
  556. text: "",
  557. toolCalls: [
  558. {
  559. id: "respond-plan-call-1",
  560. input: {
  561. summary: "权限链路进度",
  562. message: "已完成入口检查,继续验证异常路径。",
  563. },
  564. name: RESPOND_TO_COORDINATOR_TOOL_NAME,
  565. },
  566. ],
  567. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  568. };
  569. }
  570. return modelTextResult("continued child work");
  571. },
  572. } as never),
  573. },
  574. );
  575. const result = await runtime.executeTurn("respond and continue");
  576. expect(result.response).toBe("continued child work");
  577. expect(requests).toEqual([
  578. expect.objectContaining({
  579. childToolCallId: "respond-plan-call-1",
  580. message: "已完成入口检查,继续验证异常路径。",
  581. summary: "权限链路进度",
  582. }),
  583. ]);
  584. expect(requests[0]).not.toHaveProperty("childSessionId");
  585. expect(requests[0]?.trace).toMatchObject({ sessionId });
  586. });
  587. it("keeps RespondToCoordinator behind the enabled child runtime boundary", () => {
  588. const coordinatorResponsePort: CoordinatorResponsePort = {
  589. respond() {
  590. return {
  591. status: "success",
  592. responseId: "response_boundary",
  593. message: "queued",
  594. };
  595. },
  596. };
  597. const mainRuntime = createTestAgentRuntime(
  598. createSessionId("runtime-respond-main-boundary"),
  599. {},
  600. {
  601. coordinatorResponsePort,
  602. eventStore: createTestSessionEventStore(),
  603. },
  604. );
  605. const disallowedChildRuntime = createTestAgentRuntime(
  606. createSessionId("runtime-respond-disallowed-child"),
  607. {
  608. taskType: "subagent_child",
  609. toolDisallowlist: [RESPOND_TO_COORDINATOR_TOOL_NAME],
  610. },
  611. {
  612. coordinatorResponsePort,
  613. eventStore: createTestSessionEventStore(),
  614. },
  615. );
  616. const childWithoutPort = createTestAgentRuntime(
  617. createSessionId("runtime-respond-child-without-port"),
  618. { taskType: "subagent_child" },
  619. { eventStore: createTestSessionEventStore() },
  620. );
  621. expect(mainRuntime.getToolRegistry().has(RESPOND_TO_COORDINATOR_TOOL_NAME)).toBe(false);
  622. expect(disallowedChildRuntime.getToolRegistry().has(RESPOND_TO_COORDINATOR_TOOL_NAME)).toBe(
  623. false,
  624. );
  625. expect(childWithoutPort.getToolRegistry().has(RESPOND_TO_COORDINATOR_TOOL_NAME)).toBe(false);
  626. });
  627. it("keeps child work actionable after RespondToCoordinator enqueue failure", async () => {
  628. const capturedRequests: string[] = [];
  629. const enqueueError = "injected enqueue failure ".repeat(300);
  630. let modelCallCount = 0;
  631. const runtime = createTestAgentRuntime(
  632. createSessionId("runtime-respond-to-coordinator-failed"),
  633. { taskType: "subagent_child" },
  634. {
  635. coordinatorResponsePort: {
  636. respond() {
  637. return {
  638. status: "failed",
  639. responseId: "response_failed",
  640. message: "Response failed to queue.",
  641. error: enqueueError,
  642. };
  643. },
  644. },
  645. eventStore: createTestSessionEventStore(),
  646. modelFactory: createTestModelFactory({
  647. async generateText(request: { messages: Array<{ content: ModelMessageContent }> }) {
  648. modelCallCount++;
  649. capturedRequests.push(
  650. request.messages
  651. .map((message) => modelMessageContentToText(message.content))
  652. .join("\n"),
  653. );
  654. if (modelCallCount === 1) {
  655. return {
  656. finishReason: "tool-calls",
  657. model: "test",
  658. providerMetadata: undefined,
  659. text: "",
  660. toolCalls: [
  661. {
  662. id: "respond-failed-call-1",
  663. input: { summary: "progress", message: "still working" },
  664. name: RESPOND_TO_COORDINATOR_TOOL_NAME,
  665. },
  666. ],
  667. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  668. };
  669. }
  670. return modelTextResult("continued after failed response");
  671. },
  672. } as never),
  673. },
  674. );
  675. const result = await runtime.executeTurn("report progress");
  676. expect(result.response).toBe("continued after failed response");
  677. expect(capturedRequests[1]).toContain("injected enqueue failure");
  678. expect(capturedRequests[1]).toContain("Continue the current task");
  679. expect(capturedRequests[1]).toContain("Tool output truncated by resultBudget");
  680. });
  681. it("returns a configuration error when RespondToCoordinator is forced without a port", async () => {
  682. let modelCallCount = 0;
  683. const capturedRequests: string[] = [];
  684. const runtime = createTestAgentRuntime(
  685. createSessionId("runtime-respond-to-coordinator-missing-port"),
  686. { taskType: "subagent_child" },
  687. {
  688. eventStore: createTestSessionEventStore(),
  689. modelFactory: createTestModelFactory({
  690. async generateText(request: { messages: Array<{ content: ModelMessageContent }> }) {
  691. modelCallCount++;
  692. capturedRequests.push(
  693. request.messages
  694. .map((message) => modelMessageContentToText(message.content))
  695. .join("\n"),
  696. );
  697. if (modelCallCount === 1) {
  698. return {
  699. finishReason: "tool-calls",
  700. model: "test",
  701. providerMetadata: undefined,
  702. text: "",
  703. toolCalls: [
  704. {
  705. id: "respond-missing-port-call-1",
  706. input: { summary: "progress", message: "still working" },
  707. name: RESPOND_TO_COORDINATOR_TOOL_NAME,
  708. },
  709. ],
  710. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  711. };
  712. }
  713. return modelTextResult("handled configuration error");
  714. },
  715. } as never),
  716. },
  717. );
  718. runtime.getToolRegistry().register(respondToCoordinatorToolEntry);
  719. await runtime.executeTurn("force response tool");
  720. expect(capturedRequests[1]).toContain(
  721. "Coordinator response port is not configured for RespondToCoordinator",
  722. );
  723. });
  724. it("queues post-tool session mailbox context as active-turn user input", async () => {
  725. const sessionId = createSessionId("runtime-mailbox-post-tool");
  726. const targetSessionId = createSessionId("runtime-mailbox-post-tool-target");
  727. const eventStore = createTestSessionEventStore();
  728. const capturedRequests: Array<Array<{ content: ModelMessageContent; role: string }>> = [];
  729. let drainCount = 0;
  730. let modelCallCount = 0;
  731. const runtime = createTestAgentRuntime(
  732. sessionId,
  733. {},
  734. {
  735. eventStore,
  736. sessionMailboxPort: {
  737. async drainUnread() {
  738. drainCount++;
  739. if (drainCount !== 2) return [];
  740. return [
  741. {
  742. version: 1,
  743. messageId: "mail-post-tool-1",
  744. fromSessionId: targetSessionId,
  745. toSessionId: sessionId,
  746. content: "成竹在胸,请你接 胸 字开头的成语。",
  747. createdAt: new Date().toISOString(),
  748. },
  749. {
  750. version: 1,
  751. messageId: "mail-post-tool-2",
  752. fromSessionId: targetSessionId,
  753. toSessionId: sessionId,
  754. content: "胸有成竹,请你接 竹 字开头的成语。",
  755. createdAt: new Date().toISOString(),
  756. },
  757. ];
  758. },
  759. },
  760. modelFactory: createTestModelFactory({
  761. async generateText(request: {
  762. messages: Array<{ content: ModelMessageContent; role: string }>;
  763. }) {
  764. modelCallCount++;
  765. capturedRequests.push(request.messages);
  766. if (modelCallCount === 1) {
  767. return {
  768. finishReason: "tool-calls",
  769. model: "test",
  770. providerMetadata: undefined,
  771. text: "",
  772. toolCalls: [
  773. {
  774. id: "send-message-call-1",
  775. input: {
  776. to: "agent_missing_for_mailbox_test",
  777. summary: "触发 post tool mailbox drain",
  778. message: "水到渠成,请你接 成 字开头的成语。",
  779. },
  780. name: SEND_MESSAGE_TOOL_NAME,
  781. },
  782. ],
  783. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  784. };
  785. }
  786. return modelTextResult("received mailbox boundary");
  787. },
  788. } as never),
  789. },
  790. );
  791. const result = await runtime.executeTurn("start idiom chain");
  792. const toolMessage = capturedRequests.flat().find((message) => message.role === "tool");
  793. const mailboxRequestText = capturedRequests
  794. .flat()
  795. .map((message) => modelMessageContentToText(message.content))
  796. .join("\n");
  797. const events = await eventStore.getEvents(sessionId);
  798. const eventTypes = events.map((event) => event.type);
  799. expect(result.response).toBe("received mailbox boundary");
  800. expect(modelCallCount).toBeGreaterThanOrEqual(2);
  801. expect(modelMessageContentToText(toolMessage?.content ?? "")).not.toContain("<session-message");
  802. expect(mailboxRequestText).toContain("mail-post-tool-1");
  803. expect(mailboxRequestText).toContain("成竹在胸,请你接 胸 字开头的成语。");
  804. expect(mailboxRequestText).toContain("mail-post-tool-2");
  805. expect(mailboxRequestText).toContain("胸有成竹,请你接 竹 字开头的成语。");
  806. expect(eventTypes).toContain(SessionEventType.TurnSteerQueued);
  807. expect(eventTypes).toContain(SessionEventType.TurnSteerDrained);
  808. });
  809. });
  810. function modelTextResult(text: string) {
  811. return {
  812. finishReason: "stop",
  813. model: "test",
  814. providerMetadata: undefined,
  815. text,
  816. usage: {
  817. inputTokens: 1,
  818. outputTokens: 1,
  819. totalTokens: 2,
  820. },
  821. };
  822. }