runtime-hooks.test.ts 34 KB

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