tool-hook-context.test.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  1. import { mkdtemp, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { describe, expect, it } from "vitest";
  5. import {
  6. HookEventName,
  7. SessionEventType,
  8. createRootTraceContext,
  9. createSessionId,
  10. createToolCallId,
  11. createTurnId,
  12. type HookInput,
  13. type SessionEvent,
  14. type ToolArtifactStorePort,
  15. type ToolArtifactWriteRequest,
  16. } from "@zcode/contracts";
  17. import { NodeExecutionAdapter } from "../../adapters/src/exec/index.js";
  18. import { createInMemoryHookRunner } from "../src/hooks/index.js";
  19. import type { HookCallback } from "../src/hooks/types.js";
  20. import { formatMcpToolResult } from "../src/mcp/index.js";
  21. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  22. import { isErrorForToolResult } from "../src/runtime/helpers/tool-result.js";
  23. import { createToolExecutor } from "../src/tool/executor.js";
  24. import { bashToolEntry } from "../src/tool/handlers/bash.js";
  25. import { createToolRegistry } from "../src/tool/registry.js";
  26. import type { ToolEntry, ToolHandler } from "../src/tool/types.js";
  27. describe("ToolExecutor hook additional context", () => {
  28. it("keeps PreToolUse hook context out of the successful tool result", async () => {
  29. const fixture = createExecutorFixture("tool-hook-pre-context");
  30. fixture.registry.register(createTestToolEntry("ContextTool", async () => "tool-output"));
  31. const hookRunner = createInMemoryHookRunner({
  32. hooks: [
  33. {
  34. event: HookEventName.PreToolUse,
  35. matcher: "ContextTool",
  36. callback: async (input) => ({
  37. hookSpecificOutput: {
  38. additionalContext: "pre-tool context",
  39. hookEventName: input.hookEventName,
  40. },
  41. }),
  42. },
  43. ],
  44. });
  45. const executor = fixture.createExecutor(hookRunner);
  46. const result = await executor.execute(
  47. {
  48. id: createToolCallId("pre-context"),
  49. input: {},
  50. name: "ContextTool",
  51. },
  52. { traceContext: fixture.traceContext },
  53. );
  54. expect(result.success).toBe(true);
  55. expect(result.modelContent).toBe("tool-output");
  56. expect(result.serialization?.content).toBe("tool-output");
  57. expect(result.hookAdditionalContexts).toEqual([
  58. "PreToolUse:ContextTool hook additional context: pre-tool context",
  59. ]);
  60. });
  61. it("keeps the raw error as the failed tool result and carries Pre and Failure contexts", async () => {
  62. const fixture = createExecutorFixture("tool-hook-failure-context");
  63. fixture.registry.register(
  64. createTestToolEntry("FailingContextTool", async () => {
  65. throw new Error("tool exploded");
  66. }),
  67. );
  68. const hookRunner = createInMemoryHookRunner({
  69. hooks: [
  70. {
  71. event: HookEventName.PreToolUse,
  72. matcher: "FailingContextTool",
  73. callback: async (input) => ({
  74. hookSpecificOutput: {
  75. additionalContext: "pre failure context",
  76. hookEventName: input.hookEventName,
  77. },
  78. }),
  79. },
  80. {
  81. event: HookEventName.PostToolUseFailure,
  82. matcher: "FailingContextTool",
  83. callback: async (input) => ({
  84. hookSpecificOutput: {
  85. additionalContext: "post failure context",
  86. hookEventName: input.hookEventName,
  87. },
  88. }),
  89. },
  90. ],
  91. });
  92. const executor = fixture.createExecutor(hookRunner);
  93. const result = await executor.execute(
  94. {
  95. id: createToolCallId("pre-failure-context"),
  96. input: {},
  97. name: "FailingContextTool",
  98. },
  99. { traceContext: fixture.traceContext },
  100. );
  101. const withoutHooks = await fixture
  102. .createExecutor(createInMemoryHookRunner({ hooks: [] }))
  103. .execute(
  104. {
  105. id: createToolCallId("pre-failure-context-no-hooks"),
  106. input: {},
  107. name: "FailingContextTool",
  108. },
  109. { traceContext: fixture.traceContext },
  110. );
  111. expect(result.success).toBe(false);
  112. // 有 Hook 与没有 Hook 时,模型看到的是同一段错误原文。
  113. expect(result.modelContent).toEqual(withoutHooks.modelContent);
  114. expect(result.error?.message).toBe(withoutHooks.error?.message);
  115. expect(JSON.stringify(result.modelContent ?? "")).not.toContain("failure context");
  116. expect(result.hookAdditionalContexts).toEqual([
  117. "PreToolUse:FailingContextTool hook additional context: pre failure context",
  118. "PostToolUseFailure:FailingContextTool hook additional context: post failure context",
  119. ]);
  120. });
  121. it("keeps PreToolUse context when hook-updated input fails schema validation", async () => {
  122. const fixture = createExecutorFixture("tool-hook-invalid-update-context");
  123. let handlerRan = false;
  124. const entry = createTestToolEntry("InvalidHookUpdateTool", async () => {
  125. handlerRan = true;
  126. return "should-not-run";
  127. });
  128. entry.inputSchema = {
  129. additionalProperties: false,
  130. properties: { value: { type: "string" } },
  131. required: ["value"],
  132. type: "object",
  133. };
  134. fixture.registry.register(entry);
  135. const hookRunner = createInMemoryHookRunner({
  136. hooks: [
  137. {
  138. event: HookEventName.PreToolUse,
  139. matcher: "InvalidHookUpdateTool",
  140. callback: async (input) => ({
  141. hookSpecificOutput: {
  142. additionalContext: "invalid update context",
  143. hookEventName: input.hookEventName,
  144. updatedInput: {},
  145. },
  146. }),
  147. },
  148. ],
  149. });
  150. const result = await fixture.createExecutor(hookRunner).execute(
  151. {
  152. id: createToolCallId("invalid-hook-update-context"),
  153. input: { value: "valid-before-hook" },
  154. name: "InvalidHookUpdateTool",
  155. },
  156. { traceContext: fixture.traceContext },
  157. );
  158. expect(result.success).toBe(false);
  159. expect(result.error?.message).toContain(
  160. "PreToolUse hook for InvalidHookUpdateTool returned updatedInput that failed schema validation",
  161. );
  162. // 模型看到逐条问题和“模型自己的输入没错”一句,不加 <tool_use_error>(与 hook 拒绝相同)。
  163. expect(result.modelContent).toBe(
  164. [
  165. "PreToolUse hook for InvalidHookUpdateTool returned updatedInput that failed schema validation: InvalidHookUpdateTool failed due to the following issue:",
  166. "The required parameter `value` is missing",
  167. "The tool input from the model was valid; the hook's rewrite of it was not.",
  168. ].join("\n"),
  169. );
  170. expect(JSON.stringify(result.modelContent ?? "")).not.toContain("invalid update context");
  171. expect(result.hookAdditionalContexts).toEqual([
  172. "PreToolUse:InvalidHookUpdateTool hook additional context: invalid update context",
  173. ]);
  174. expect(handlerRan).toBe(false);
  175. });
  176. it("routes a handler failure through the existing failure lifecycle", async () => {
  177. const fixture = createExecutorFixture("tool-handler-failure");
  178. let handlerCalls = 0;
  179. let postSuccessRan = false;
  180. let postFailureRan = false;
  181. fixture.registry.register(
  182. createTestToolEntry("HandlerFailureTool", async () => {
  183. handlerCalls += 1;
  184. return {
  185. result: false,
  186. errorCode: 7,
  187. message: "Tool-specific failure",
  188. };
  189. }),
  190. );
  191. const hookRunner = createInMemoryHookRunner({
  192. hooks: [
  193. {
  194. event: HookEventName.PreToolUse,
  195. matcher: "HandlerFailureTool",
  196. callback: async (input) => ({
  197. hookSpecificOutput: {
  198. additionalContext: "pre failure context",
  199. hookEventName: input.hookEventName,
  200. },
  201. }),
  202. },
  203. {
  204. event: HookEventName.PostToolUse,
  205. matcher: "HandlerFailureTool",
  206. callback: async () => {
  207. postSuccessRan = true;
  208. return {};
  209. },
  210. },
  211. {
  212. event: HookEventName.PostToolUseFailure,
  213. matcher: "HandlerFailureTool",
  214. callback: async (input) => {
  215. postFailureRan = true;
  216. return {
  217. hookSpecificOutput: {
  218. additionalContext: "post failure context",
  219. hookEventName: input.hookEventName,
  220. },
  221. };
  222. },
  223. },
  224. ],
  225. });
  226. const result = await fixture.createExecutor(hookRunner).execute(
  227. {
  228. id: createToolCallId("handler-failure"),
  229. input: {},
  230. name: "HandlerFailureTool",
  231. },
  232. { traceContext: fixture.traceContext },
  233. );
  234. expect(result.success).toBe(false);
  235. expect(result.error).toMatchObject({
  236. code: "7",
  237. message: "Tool-specific failure",
  238. });
  239. expect(result.modelContent).toBe("<tool_use_error>Tool-specific failure</tool_use_error>");
  240. expect(result.hookAdditionalContexts).toEqual([
  241. "PreToolUse:HandlerFailureTool hook additional context: pre failure context",
  242. "PostToolUseFailure:HandlerFailureTool hook additional context: post failure context",
  243. ]);
  244. expect(handlerCalls).toBe(1);
  245. expect(postSuccessRan).toBe(false);
  246. expect(postFailureRan).toBe(true);
  247. expect(fixture.events.map((event) => event.type)).toEqual([
  248. SessionEventType.ToolCallStarted,
  249. SessionEventType.ToolCallError,
  250. ]);
  251. });
  252. it("records non-blocking PostToolUse continue false without failing the tool", async () => {
  253. const fixture = createExecutorFixture("tool-hook-post-continue-false");
  254. const events: SessionEvent[] = [];
  255. let handlerRan = false;
  256. fixture.registry.register(
  257. createTestToolEntry("PostContinueTool", async () => {
  258. handlerRan = true;
  259. return "tool-output";
  260. }),
  261. );
  262. const hookRunner = createInMemoryHookRunner({
  263. emitEvent: async (event) => {
  264. events.push(event);
  265. },
  266. hooks: [
  267. {
  268. event: HookEventName.PostToolUse,
  269. matcher: "PostContinueTool",
  270. callback: async (input) => ({
  271. continue: false,
  272. reason: "post hook requested stop",
  273. hookSpecificOutput: {
  274. hookEventName: input.hookEventName,
  275. },
  276. }),
  277. },
  278. ],
  279. });
  280. const executor = fixture.createExecutor(hookRunner);
  281. const result = await executor.execute(
  282. {
  283. id: createToolCallId("post-continue-false"),
  284. input: {},
  285. name: "PostContinueTool",
  286. },
  287. { traceContext: fixture.traceContext },
  288. );
  289. expect(result.success).toBe(true);
  290. expect(handlerRan).toBe(true);
  291. expect(events.map((event) => event.type)).toEqual([
  292. // D20:block 决策只产生一个终态事件(runner.ts:143 为 blocked ? Blocked : Completed)。
  293. // 此前同时断言 Completed + Blocked,会让「被拦截」在 UI 上呈现为已完成绿勾。
  294. SessionEventType.HookRunStarted,
  295. SessionEventType.HookRunBlocked,
  296. ]);
  297. });
  298. it("matches Task hook matcher aliases without rewriting the Agent hook input", async () => {
  299. const fixture = createExecutorFixture("tool-hook-task-agent-alias");
  300. fixture.registry.register(createTestToolEntry("Agent", async () => "agent-output"));
  301. let observedToolName: string | undefined;
  302. const hookRunner = createInMemoryHookRunner({
  303. hooks: [
  304. {
  305. event: HookEventName.PreToolUse,
  306. matcher: "Task",
  307. callback: async (input) => {
  308. observedToolName = "toolName" in input ? input.toolName : undefined;
  309. return {
  310. hookSpecificOutput: {
  311. additionalContext: "task matcher matched agent",
  312. hookEventName: input.hookEventName,
  313. },
  314. };
  315. },
  316. },
  317. ],
  318. });
  319. const executor = fixture.createExecutor(hookRunner);
  320. const result = await executor.execute(
  321. {
  322. id: createToolCallId("agent-task-matcher"),
  323. input: {},
  324. name: "Agent",
  325. },
  326. { traceContext: fixture.traceContext },
  327. );
  328. expect(result.success).toBe(true);
  329. expect(result.hookAdditionalContexts).toEqual([
  330. "PreToolUse:Agent hook additional context: task matcher matched agent",
  331. ]);
  332. expect(observedToolName).toBe("Agent");
  333. });
  334. it("matches Agent hook matcher aliases without rewriting the Task hook input", async () => {
  335. const fixture = createExecutorFixture("tool-hook-agent-task-alias");
  336. fixture.registry.register(createTestToolEntry("Task", async () => "task-output"));
  337. let observedToolName: string | undefined;
  338. const hookRunner = createInMemoryHookRunner({
  339. hooks: [
  340. {
  341. event: HookEventName.PreToolUse,
  342. matcher: "Agent",
  343. callback: async (input) => {
  344. observedToolName = "toolName" in input ? input.toolName : undefined;
  345. return {
  346. hookSpecificOutput: {
  347. additionalContext: "agent matcher matched task",
  348. hookEventName: input.hookEventName,
  349. },
  350. };
  351. },
  352. },
  353. ],
  354. });
  355. const executor = fixture.createExecutor(hookRunner);
  356. const result = await executor.execute(
  357. {
  358. id: createToolCallId("task-agent-matcher"),
  359. input: {},
  360. name: "Task",
  361. },
  362. { traceContext: fixture.traceContext },
  363. );
  364. expect(result.success).toBe(true);
  365. expect(result.hookAdditionalContexts).toEqual([
  366. "PreToolUse:Task hook additional context: agent matcher matched task",
  367. ]);
  368. expect(observedToolName).toBe("Task");
  369. });
  370. });
  371. // hooks.md「失败的定义」:handler 正常返回、但结果是错误结果时,只运行 PostToolUseFailure;
  372. // 判定与 tool_result 的 is_error 相同。真实 Bash 在全量并发下单次可到 4 秒以上,放宽到 15 秒。
  373. describe.skipIf(process.platform === "win32")(
  374. "ToolExecutor hook event for error results",
  375. { timeout: 15_000 },
  376. () => {
  377. it("runs only PostToolUseFailure for a failed Bash command and passes the model text", async () => {
  378. const run = await runBashWithHooks(
  379. "hook-bash-failure",
  380. (root) => `ls ${join(root, "deliberately-nonexistent")}`,
  381. );
  382. expect(run.result.success).toBe(true);
  383. expect(isErrorForToolResult(run.result)).toBe(true);
  384. const modelText = String(run.result.modelContent);
  385. // ls 的退出码随系统不同(macOS 1,Linux 2)。
  386. expect(modelText).toMatch(/^Exit code \d+\nls: .*deliberately-nonexistent/u);
  387. expect(run.postInputs).toHaveLength(0);
  388. expect(run.failureInputs).toHaveLength(1);
  389. expect(run.failureInputs[0]).toMatchObject({
  390. error: { message: modelText, type: "tool_execution_failed" },
  391. hookEventName: HookEventName.PostToolUseFailure,
  392. isInterrupt: false,
  393. toolName: "Bash",
  394. });
  395. expect(run.failureInputs[0]).not.toHaveProperty("toolResponse");
  396. expect(run.result.hookAdditionalContexts).toEqual([
  397. "PostToolUseFailure:Bash hook additional context: AUDIT_PostToolUseFailure",
  398. ]);
  399. });
  400. it("runs only PostToolUseFailure for a Bash hard timeout, which is not an interrupt", async () => {
  401. const run = await runBashWithHooks(
  402. "hook-bash-timeout",
  403. () => "sleep 0.2; printf unexpected",
  404. {
  405. timeout: 10,
  406. },
  407. );
  408. expect(isErrorForToolResult(run.result)).toBe(true);
  409. const modelText = String(run.result.modelContent);
  410. expect(modelText).toMatch(/^Exit code 143\nCommand timed out after /u);
  411. expect(run.postInputs).toHaveLength(0);
  412. expect(run.failureInputs).toHaveLength(1);
  413. expect(run.failureInputs[0]).toMatchObject({
  414. error: { message: modelText, type: "tool_execution_failed" },
  415. isInterrupt: false,
  416. });
  417. });
  418. it("runs PostToolUse when grep exits 1 without matches", async () => {
  419. const run = await runBashWithHooks(
  420. "hook-grep-nomatch",
  421. (root) => `grep AUDIT_NO_SUCH_TEXT ${join(root, "sample.txt")}`,
  422. );
  423. expect(isErrorForToolResult(run.result)).toBe(false);
  424. expect(run.failureInputs).toHaveLength(0);
  425. expect(run.postInputs).toHaveLength(1);
  426. expect(run.result.hookAdditionalContexts).toEqual([
  427. "PostToolUse:Bash hook additional context: AUDIT_PostToolUse",
  428. ]);
  429. });
  430. },
  431. );
  432. // MCP 用例不调用 Bash,Windows 上也要跑。
  433. describe("ToolExecutor hook event for an MCP error result", () => {
  434. it("runs only PostToolUseFailure when an MCP result has isError", async () => {
  435. const fixture = createExecutorFixture("hook-mcp-is-error");
  436. fixture.registry.register({
  437. ...createTestToolEntry("mcp__audit__quota", async () => ({
  438. content: [{ type: "text", text: "quota exhausted" }],
  439. isError: true,
  440. })),
  441. formatModelContent: formatMcpToolResult,
  442. outputSchema: { type: "object" },
  443. });
  444. const hooks = createRecordingHooks("mcp__audit__quota");
  445. const result = await fixture
  446. .createExecutor(hooks.hookRunner)
  447. .execute(
  448. { id: createToolCallId("hook-mcp-is-error-call"), input: {}, name: "mcp__audit__quota" },
  449. { traceContext: fixture.traceContext },
  450. );
  451. expect(isErrorForToolResult(result)).toBe(true);
  452. expect(result.modelContent).toBe("MCP tool returned an error:\nquota exhausted");
  453. expect(hooks.postInputs).toHaveLength(0);
  454. expect(hooks.failureInputs).toHaveLength(1);
  455. expect(hooks.failureInputs[0]).toMatchObject({
  456. error: { message: "MCP tool returned an error:\nquota exhausted" },
  457. isInterrupt: false,
  458. });
  459. expect(result.hookAdditionalContexts).toEqual([
  460. "PostToolUseFailure:mcp__audit__quota hook additional context: AUDIT_PostToolUseFailure",
  461. ]);
  462. });
  463. });
  464. async function runBashWithHooks(
  465. sessionName: string,
  466. command: (root: string) => string,
  467. extraInput: Record<string, unknown> = {},
  468. ) {
  469. const root = await mkdtemp(join(tmpdir(), "zcode-hook-error-result-"));
  470. await writeFile(join(root, "sample.txt"), "AUDIT_SAMPLE first line\n");
  471. const executionPort = new NodeExecutionAdapter({ outputRootDir: root });
  472. const fixture = createExecutorFixture(sessionName);
  473. fixture.registry.register(bashToolEntry);
  474. const hooks = createRecordingHooks("Bash");
  475. try {
  476. const result = await createToolExecutor({
  477. emitEvent: async () => {},
  478. executionPort,
  479. hookRunner: hooks.hookRunner,
  480. mode: "yolo",
  481. permissionBroker: {
  482. async requestPermission() {
  483. return { decision: "allow" as const };
  484. },
  485. },
  486. permissionService: new PermissionService(defaultPermissionConfig),
  487. registry: fixture.registry,
  488. sessionId: fixture.traceContext.sessionId!,
  489. traceContext: fixture.traceContext,
  490. turnId: fixture.traceContext.turnId!,
  491. workingDirectory: root,
  492. }).execute(
  493. {
  494. id: createToolCallId(`${sessionName}-call`),
  495. input: { command: command(root), description: "Audit exit status", ...extraInput },
  496. name: "Bash",
  497. },
  498. { traceContext: fixture.traceContext },
  499. );
  500. return { result, ...hooks };
  501. } finally {
  502. await executionPort.close();
  503. await rm(root, { recursive: true, force: true });
  504. }
  505. }
  506. // PostToolUse 与 PostToolUseFailure 各挂一个记录输入、返回固定 context 的 Hook。
  507. function createRecordingHooks(matcher: string) {
  508. const postInputs: HookInput[] = [];
  509. const failureInputs: HookInput[] = [];
  510. const recordingHook =
  511. (inputs: HookInput[]): HookCallback =>
  512. async (input) => {
  513. inputs.push(input);
  514. return {
  515. hookSpecificOutput: {
  516. additionalContext: `AUDIT_${input.hookEventName}`,
  517. hookEventName: input.hookEventName,
  518. },
  519. };
  520. };
  521. const hookRunner = createInMemoryHookRunner({
  522. hooks: [
  523. { event: HookEventName.PostToolUse, matcher, callback: recordingHook(postInputs) },
  524. { event: HookEventName.PostToolUseFailure, matcher, callback: recordingHook(failureInputs) },
  525. ],
  526. });
  527. return { failureInputs, hookRunner, postInputs };
  528. }
  529. describe("ToolExecutor hook additional context size cap", () => {
  530. it("keeps a context of exactly 10000 chars unchanged", async () => {
  531. const context = "a".repeat(10_000);
  532. const store = createHookArtifactStore();
  533. const result = await executeWithPostContext("tool-hook-cap-exact", context, store);
  534. expect(store.requests).toHaveLength(0);
  535. expect(result.hookAdditionalContexts).toEqual([
  536. `PostToolUse:CapTool hook additional context: ${context}`,
  537. ]);
  538. });
  539. it("persists a longer context and shows a persisted-output preview", async () => {
  540. const context = "a".repeat(12_000);
  541. const store = createHookArtifactStore();
  542. const result = await executeWithPostContext("tool-hook-cap-persist", context, store);
  543. expect(store.requests).toHaveLength(1);
  544. expect(store.requests[0]).toMatchObject({ content: context, contentType: "text/plain" });
  545. expect(result.hookAdditionalContexts).toEqual([
  546. "PostToolUse:CapTool hook additional context: <persisted-output>\n" +
  547. "Output too large (11.7KB). Full output saved to: /artifacts/hook-1.txt\n\n" +
  548. `Preview (first 2KB):\n${"a".repeat(2_000)}\n...\n</persisted-output>`,
  549. ]);
  550. });
  551. it("keeps the first 10000 chars and the reason when the write fails", async () => {
  552. const context = `${"a".repeat(9_999)}😀tail`;
  553. const store = createHookArtifactStore(new Error("disk full"));
  554. const result = await executeWithPostContext("tool-hook-cap-write-failed", context, store);
  555. // 第 10000 个字符是代理对的高位,截断时一起去掉,不留半个字符。
  556. expect(result.hookAdditionalContexts).toEqual([
  557. `PostToolUse:CapTool hook additional context: ${"a".repeat(9_999)}\n\n` +
  558. "[Hook additionalContext truncated at 10000 chars — persist-to-disk failed: disk full]",
  559. ]);
  560. });
  561. it("reuses the formatted PreToolUse context when the success path throws after formatting", async () => {
  562. const fixture = createExecutorFixture("tool-hook-cap-late-failure");
  563. fixture.registry.register(createTestToolEntry("CapTool", async () => "tool-output"));
  564. const context = "c".repeat(12_000);
  565. const store = createHookArtifactStore();
  566. const executor = createToolExecutor({
  567. artifactStore: store,
  568. // 成功路径格式化 Hook 上下文之后,写结果事件时失败,进入 catch。
  569. emitEvent: async (event) => {
  570. if (event.type === SessionEventType.ToolCallResult) throw new Error("event store down");
  571. },
  572. hookRunner: createInMemoryHookRunner({
  573. hooks: [
  574. {
  575. event: HookEventName.PreToolUse,
  576. matcher: "CapTool",
  577. callback: async (input) => ({
  578. hookSpecificOutput: {
  579. additionalContext: context,
  580. hookEventName: input.hookEventName,
  581. },
  582. }),
  583. },
  584. ],
  585. }),
  586. permissionService: new PermissionService(defaultPermissionConfig),
  587. registry: fixture.registry,
  588. sessionId: fixture.traceContext.sessionId!,
  589. traceContext: fixture.traceContext,
  590. turnId: fixture.traceContext.turnId!,
  591. });
  592. const result = await executor.execute(
  593. { id: createToolCallId("cap-late-failure"), input: {}, name: "CapTool" },
  594. { traceContext: fixture.traceContext },
  595. );
  596. // catch 复用成功路径已过滤、已格式化的结果:只落盘一次,附件指向同一个文件。
  597. expect(result.success).toBe(false);
  598. expect(store.requests).toHaveLength(1);
  599. expect(result.hookAdditionalContexts).toEqual([
  600. expect.stringContaining("Full output saved to: /artifacts/hook-1.txt"),
  601. ]);
  602. });
  603. it("caps the PreToolUse context on the deny path", async () => {
  604. const fixture = createExecutorFixture("tool-hook-cap-deny");
  605. fixture.registry.register(createTestToolEntry("CapTool", async () => "tool-output"));
  606. const context = "b".repeat(10_001);
  607. const result = await fixture
  608. .createExecutor(
  609. createInMemoryHookRunner({
  610. hooks: [
  611. {
  612. event: HookEventName.PreToolUse,
  613. matcher: "CapTool",
  614. callback: async (input) => ({
  615. hookSpecificOutput: {
  616. additionalContext: context,
  617. hookEventName: input.hookEventName,
  618. permissionDecision: "deny",
  619. },
  620. }),
  621. },
  622. ],
  623. }),
  624. )
  625. .execute(
  626. { id: createToolCallId("cap-deny"), input: {}, name: "CapTool" },
  627. { traceContext: fixture.traceContext },
  628. );
  629. expect(result.success).toBe(false);
  630. expect(result.hookAdditionalContexts).toEqual([
  631. `PreToolUse:CapTool hook additional context: ${"b".repeat(10_000)}\n\n` +
  632. "[Hook additionalContext truncated at 10000 chars — persist-to-disk failed: no artifact store]",
  633. ]);
  634. });
  635. });
  636. async function executeWithPostContext(
  637. sessionName: string,
  638. context: string,
  639. artifactStore: ToolArtifactStorePort,
  640. ) {
  641. const fixture = createExecutorFixture(sessionName);
  642. fixture.registry.register(createTestToolEntry("CapTool", async () => "tool-output"));
  643. const hookRunner = createInMemoryHookRunner({
  644. hooks: [
  645. {
  646. event: HookEventName.PostToolUse,
  647. matcher: "CapTool",
  648. callback: async (input) => ({
  649. hookSpecificOutput: { additionalContext: context, hookEventName: input.hookEventName },
  650. }),
  651. },
  652. ],
  653. });
  654. return fixture
  655. .createExecutor(hookRunner, artifactStore)
  656. .execute(
  657. { id: createToolCallId(`${sessionName}-call`), input: {}, name: "CapTool" },
  658. { traceContext: fixture.traceContext },
  659. );
  660. }
  661. function createHookArtifactStore(writeError?: Error) {
  662. const requests: ToolArtifactWriteRequest[] = [];
  663. const store: ToolArtifactStorePort & { requests: ToolArtifactWriteRequest[] } = {
  664. requests,
  665. async writeToolResultArtifact(request) {
  666. if (writeError) throw writeError;
  667. requests.push(request);
  668. return {
  669. bytes: Buffer.byteLength(request.content, "utf8"),
  670. contentType: request.contentType ?? "text/plain",
  671. createdAt: new Date(),
  672. id: `hook-${requests.length}`,
  673. path: `/artifacts/hook-${requests.length}.txt`,
  674. uri: `zcode-artifact://test/hook-${requests.length}`,
  675. };
  676. },
  677. async readToolResultArtifact() {
  678. throw new Error("not used");
  679. },
  680. };
  681. return store;
  682. }
  683. function createExecutorFixture(sessionName: string) {
  684. const sessionId = createSessionId(sessionName);
  685. const turnId = createTurnId("tool-hook-context-turn");
  686. const traceContext = createRootTraceContext({ sessionId, turnId });
  687. const registry = createToolRegistry();
  688. const events: SessionEvent[] = [];
  689. return {
  690. events,
  691. registry,
  692. traceContext,
  693. createExecutor(
  694. hookRunner: ReturnType<typeof createInMemoryHookRunner>,
  695. artifactStore?: ToolArtifactStorePort,
  696. ) {
  697. return createToolExecutor({
  698. artifactStore,
  699. emitEvent: async (event) => {
  700. events.push(event);
  701. },
  702. hookRunner,
  703. permissionService: new PermissionService(defaultPermissionConfig),
  704. registry,
  705. sessionId,
  706. traceContext,
  707. turnId,
  708. });
  709. },
  710. };
  711. }
  712. function createTestToolEntry(name: string, handler: ToolHandler): ToolEntry {
  713. return {
  714. capability: `${name} test capability`,
  715. handler,
  716. inputSchema: {
  717. additionalProperties: true,
  718. type: "object",
  719. },
  720. metadata: {
  721. concurrentSafe: true,
  722. destructive: false,
  723. name,
  724. needsApproval: false,
  725. readOnly: true,
  726. riskLevel: "low",
  727. sideEffectScope: "none",
  728. timeoutMs: 30000,
  729. },
  730. outputSchema: {
  731. type: "string",
  732. },
  733. permission: {
  734. denyPriority: "beforeAsk",
  735. needsApproval: false,
  736. patternSources: ["none"],
  737. permission: "test",
  738. reason: "test tool",
  739. riskLevel: "low",
  740. sideEffectScope: "none",
  741. },
  742. resultBudget: {
  743. maxInlineBytes: 100_000,
  744. maxModelBytes: 100_000,
  745. strategy: "truncate",
  746. },
  747. };
  748. }