tool-hook-context.test.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. HookEventName,
  4. SessionEventType,
  5. createRootTraceContext,
  6. createSessionId,
  7. createToolCallId,
  8. createTurnId,
  9. type SessionEvent,
  10. type ToolArtifactStorePort,
  11. type ToolArtifactWriteRequest,
  12. } from "@zcode/contracts";
  13. import { createInMemoryHookRunner } from "../src/hooks/index.js";
  14. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  15. import { createToolExecutor } from "../src/tool/executor.js";
  16. import { createToolRegistry } from "../src/tool/registry.js";
  17. import type { ToolEntry, ToolHandler } from "../src/tool/types.js";
  18. describe("ToolExecutor hook additional context", () => {
  19. it("keeps PreToolUse hook context out of the successful tool result", async () => {
  20. const fixture = createExecutorFixture("tool-hook-pre-context");
  21. fixture.registry.register(createTestToolEntry("ContextTool", async () => "tool-output"));
  22. const hookRunner = createInMemoryHookRunner({
  23. hooks: [
  24. {
  25. event: HookEventName.PreToolUse,
  26. matcher: "ContextTool",
  27. callback: async (input) => ({
  28. hookSpecificOutput: {
  29. additionalContext: "pre-tool context",
  30. hookEventName: input.hookEventName,
  31. },
  32. }),
  33. },
  34. ],
  35. });
  36. const executor = fixture.createExecutor(hookRunner);
  37. const result = await executor.execute(
  38. {
  39. id: createToolCallId("pre-context"),
  40. input: {},
  41. name: "ContextTool",
  42. },
  43. { traceContext: fixture.traceContext },
  44. );
  45. expect(result.success).toBe(true);
  46. expect(result.modelContent).toBe("tool-output");
  47. expect(result.serialization?.content).toBe("tool-output");
  48. expect(result.hookAdditionalContexts).toEqual([
  49. "PreToolUse:ContextTool hook additional context: pre-tool context",
  50. ]);
  51. });
  52. it("keeps the raw error as the failed tool result and carries Pre and Failure contexts", async () => {
  53. const fixture = createExecutorFixture("tool-hook-failure-context");
  54. fixture.registry.register(
  55. createTestToolEntry("FailingContextTool", async () => {
  56. throw new Error("tool exploded");
  57. }),
  58. );
  59. const hookRunner = createInMemoryHookRunner({
  60. hooks: [
  61. {
  62. event: HookEventName.PreToolUse,
  63. matcher: "FailingContextTool",
  64. callback: async (input) => ({
  65. hookSpecificOutput: {
  66. additionalContext: "pre failure context",
  67. hookEventName: input.hookEventName,
  68. },
  69. }),
  70. },
  71. {
  72. event: HookEventName.PostToolUseFailure,
  73. matcher: "FailingContextTool",
  74. callback: async (input) => ({
  75. hookSpecificOutput: {
  76. additionalContext: "post failure context",
  77. hookEventName: input.hookEventName,
  78. },
  79. }),
  80. },
  81. ],
  82. });
  83. const executor = fixture.createExecutor(hookRunner);
  84. const result = await executor.execute(
  85. {
  86. id: createToolCallId("pre-failure-context"),
  87. input: {},
  88. name: "FailingContextTool",
  89. },
  90. { traceContext: fixture.traceContext },
  91. );
  92. const withoutHooks = await fixture
  93. .createExecutor(createInMemoryHookRunner({ hooks: [] }))
  94. .execute(
  95. {
  96. id: createToolCallId("pre-failure-context-no-hooks"),
  97. input: {},
  98. name: "FailingContextTool",
  99. },
  100. { traceContext: fixture.traceContext },
  101. );
  102. expect(result.success).toBe(false);
  103. // 有 Hook 与没有 Hook 时,模型看到的是同一段错误原文。
  104. expect(result.modelContent).toEqual(withoutHooks.modelContent);
  105. expect(result.error?.message).toBe(withoutHooks.error?.message);
  106. expect(JSON.stringify(result.modelContent ?? "")).not.toContain("failure context");
  107. expect(result.hookAdditionalContexts).toEqual([
  108. "PreToolUse:FailingContextTool hook additional context: pre failure context",
  109. "PostToolUseFailure:FailingContextTool hook additional context: post failure context",
  110. ]);
  111. });
  112. it("keeps PreToolUse context when hook-updated input fails schema validation", async () => {
  113. const fixture = createExecutorFixture("tool-hook-invalid-update-context");
  114. let handlerRan = false;
  115. const entry = createTestToolEntry("InvalidHookUpdateTool", async () => {
  116. handlerRan = true;
  117. return "should-not-run";
  118. });
  119. entry.inputSchema = {
  120. additionalProperties: false,
  121. properties: { value: { type: "string" } },
  122. required: ["value"],
  123. type: "object",
  124. };
  125. fixture.registry.register(entry);
  126. const hookRunner = createInMemoryHookRunner({
  127. hooks: [
  128. {
  129. event: HookEventName.PreToolUse,
  130. matcher: "InvalidHookUpdateTool",
  131. callback: async (input) => ({
  132. hookSpecificOutput: {
  133. additionalContext: "invalid update context",
  134. hookEventName: input.hookEventName,
  135. updatedInput: {},
  136. },
  137. }),
  138. },
  139. ],
  140. });
  141. const result = await fixture.createExecutor(hookRunner).execute(
  142. {
  143. id: createToolCallId("invalid-hook-update-context"),
  144. input: { value: "valid-before-hook" },
  145. name: "InvalidHookUpdateTool",
  146. },
  147. { traceContext: fixture.traceContext },
  148. );
  149. expect(result.success).toBe(false);
  150. expect(result.error?.message).toContain("Tool input failed inputSchema validation");
  151. expect(JSON.stringify(result.modelContent ?? "")).not.toContain("invalid update context");
  152. expect(result.hookAdditionalContexts).toEqual([
  153. "PreToolUse:InvalidHookUpdateTool hook additional context: invalid update context",
  154. ]);
  155. expect(handlerRan).toBe(false);
  156. });
  157. it("routes a handler failure through the existing failure lifecycle", async () => {
  158. const fixture = createExecutorFixture("tool-handler-failure");
  159. let handlerCalls = 0;
  160. let postSuccessRan = false;
  161. let postFailureRan = false;
  162. fixture.registry.register(
  163. createTestToolEntry("HandlerFailureTool", async () => {
  164. handlerCalls += 1;
  165. return {
  166. result: false,
  167. errorCode: 7,
  168. message: "Tool-specific failure",
  169. };
  170. }),
  171. );
  172. const hookRunner = createInMemoryHookRunner({
  173. hooks: [
  174. {
  175. event: HookEventName.PreToolUse,
  176. matcher: "HandlerFailureTool",
  177. callback: async (input) => ({
  178. hookSpecificOutput: {
  179. additionalContext: "pre failure context",
  180. hookEventName: input.hookEventName,
  181. },
  182. }),
  183. },
  184. {
  185. event: HookEventName.PostToolUse,
  186. matcher: "HandlerFailureTool",
  187. callback: async () => {
  188. postSuccessRan = true;
  189. return {};
  190. },
  191. },
  192. {
  193. event: HookEventName.PostToolUseFailure,
  194. matcher: "HandlerFailureTool",
  195. callback: async (input) => {
  196. postFailureRan = true;
  197. return {
  198. hookSpecificOutput: {
  199. additionalContext: "post failure context",
  200. hookEventName: input.hookEventName,
  201. },
  202. };
  203. },
  204. },
  205. ],
  206. });
  207. const result = await fixture.createExecutor(hookRunner).execute(
  208. {
  209. id: createToolCallId("handler-failure"),
  210. input: {},
  211. name: "HandlerFailureTool",
  212. },
  213. { traceContext: fixture.traceContext },
  214. );
  215. expect(result.success).toBe(false);
  216. expect(result.error).toMatchObject({
  217. code: "7",
  218. message: "Tool-specific failure",
  219. });
  220. expect(result.modelContent).toBe("<tool_use_error>Tool-specific failure</tool_use_error>");
  221. expect(result.hookAdditionalContexts).toEqual([
  222. "PreToolUse:HandlerFailureTool hook additional context: pre failure context",
  223. "PostToolUseFailure:HandlerFailureTool hook additional context: post failure context",
  224. ]);
  225. expect(handlerCalls).toBe(1);
  226. expect(postSuccessRan).toBe(false);
  227. expect(postFailureRan).toBe(true);
  228. expect(fixture.events.map((event) => event.type)).toEqual([
  229. SessionEventType.ToolCallStarted,
  230. SessionEventType.ToolCallError,
  231. ]);
  232. });
  233. it("records non-blocking PostToolUse continue false without failing the tool", async () => {
  234. const fixture = createExecutorFixture("tool-hook-post-continue-false");
  235. const events: SessionEvent[] = [];
  236. let handlerRan = false;
  237. fixture.registry.register(
  238. createTestToolEntry("PostContinueTool", async () => {
  239. handlerRan = true;
  240. return "tool-output";
  241. }),
  242. );
  243. const hookRunner = createInMemoryHookRunner({
  244. emitEvent: async (event) => {
  245. events.push(event);
  246. },
  247. hooks: [
  248. {
  249. event: HookEventName.PostToolUse,
  250. matcher: "PostContinueTool",
  251. callback: async (input) => ({
  252. continue: false,
  253. reason: "post hook requested stop",
  254. hookSpecificOutput: {
  255. hookEventName: input.hookEventName,
  256. },
  257. }),
  258. },
  259. ],
  260. });
  261. const executor = fixture.createExecutor(hookRunner);
  262. const result = await executor.execute(
  263. {
  264. id: createToolCallId("post-continue-false"),
  265. input: {},
  266. name: "PostContinueTool",
  267. },
  268. { traceContext: fixture.traceContext },
  269. );
  270. expect(result.success).toBe(true);
  271. expect(handlerRan).toBe(true);
  272. expect(events.map((event) => event.type)).toEqual([
  273. // D20:block 决策只产生一个终态事件(runner.ts:143 为 blocked ? Blocked : Completed)。
  274. // 此前同时断言 Completed + Blocked,会让「被拦截」在 UI 上呈现为已完成绿勾。
  275. SessionEventType.HookRunStarted,
  276. SessionEventType.HookRunBlocked,
  277. ]);
  278. });
  279. it("matches Task hook matcher aliases without rewriting the Agent hook input", async () => {
  280. const fixture = createExecutorFixture("tool-hook-task-agent-alias");
  281. fixture.registry.register(createTestToolEntry("Agent", async () => "agent-output"));
  282. let observedToolName: string | undefined;
  283. const hookRunner = createInMemoryHookRunner({
  284. hooks: [
  285. {
  286. event: HookEventName.PreToolUse,
  287. matcher: "Task",
  288. callback: async (input) => {
  289. observedToolName = "toolName" in input ? input.toolName : undefined;
  290. return {
  291. hookSpecificOutput: {
  292. additionalContext: "task matcher matched agent",
  293. hookEventName: input.hookEventName,
  294. },
  295. };
  296. },
  297. },
  298. ],
  299. });
  300. const executor = fixture.createExecutor(hookRunner);
  301. const result = await executor.execute(
  302. {
  303. id: createToolCallId("agent-task-matcher"),
  304. input: {},
  305. name: "Agent",
  306. },
  307. { traceContext: fixture.traceContext },
  308. );
  309. expect(result.success).toBe(true);
  310. expect(result.hookAdditionalContexts).toEqual([
  311. "PreToolUse:Agent hook additional context: task matcher matched agent",
  312. ]);
  313. expect(observedToolName).toBe("Agent");
  314. });
  315. it("matches Agent hook matcher aliases without rewriting the Task hook input", async () => {
  316. const fixture = createExecutorFixture("tool-hook-agent-task-alias");
  317. fixture.registry.register(createTestToolEntry("Task", async () => "task-output"));
  318. let observedToolName: string | undefined;
  319. const hookRunner = createInMemoryHookRunner({
  320. hooks: [
  321. {
  322. event: HookEventName.PreToolUse,
  323. matcher: "Agent",
  324. callback: async (input) => {
  325. observedToolName = "toolName" in input ? input.toolName : undefined;
  326. return {
  327. hookSpecificOutput: {
  328. additionalContext: "agent matcher matched task",
  329. hookEventName: input.hookEventName,
  330. },
  331. };
  332. },
  333. },
  334. ],
  335. });
  336. const executor = fixture.createExecutor(hookRunner);
  337. const result = await executor.execute(
  338. {
  339. id: createToolCallId("task-agent-matcher"),
  340. input: {},
  341. name: "Task",
  342. },
  343. { traceContext: fixture.traceContext },
  344. );
  345. expect(result.success).toBe(true);
  346. expect(result.hookAdditionalContexts).toEqual([
  347. "PreToolUse:Task hook additional context: agent matcher matched task",
  348. ]);
  349. expect(observedToolName).toBe("Task");
  350. });
  351. });
  352. describe("ToolExecutor hook additional context size cap", () => {
  353. it("keeps a context of exactly 10000 chars unchanged", async () => {
  354. const context = "a".repeat(10_000);
  355. const store = createHookArtifactStore();
  356. const result = await executeWithPostContext("tool-hook-cap-exact", context, store);
  357. expect(store.requests).toHaveLength(0);
  358. expect(result.hookAdditionalContexts).toEqual([
  359. `PostToolUse:CapTool hook additional context: ${context}`,
  360. ]);
  361. });
  362. it("persists a longer context and shows a persisted-output preview", async () => {
  363. const context = "a".repeat(12_000);
  364. const store = createHookArtifactStore();
  365. const result = await executeWithPostContext("tool-hook-cap-persist", context, store);
  366. expect(store.requests).toHaveLength(1);
  367. expect(store.requests[0]).toMatchObject({ content: context, contentType: "text/plain" });
  368. expect(result.hookAdditionalContexts).toEqual([
  369. "PostToolUse:CapTool hook additional context: <persisted-output>\n" +
  370. "Output too large (11.7KB). Full output saved to: /artifacts/hook-1.txt\n\n" +
  371. `Preview (first 2KB):\n${"a".repeat(2_000)}\n...\n</persisted-output>`,
  372. ]);
  373. });
  374. it("keeps the first 10000 chars and the reason when the write fails", async () => {
  375. const context = `${"a".repeat(9_999)}😀tail`;
  376. const store = createHookArtifactStore(new Error("disk full"));
  377. const result = await executeWithPostContext("tool-hook-cap-write-failed", context, store);
  378. // 第 10000 个字符是代理对的高位,截断时一起去掉,不留半个字符。
  379. expect(result.hookAdditionalContexts).toEqual([
  380. `PostToolUse:CapTool hook additional context: ${"a".repeat(9_999)}\n\n` +
  381. "[Hook additionalContext truncated at 10000 chars — persist-to-disk failed: disk full]",
  382. ]);
  383. });
  384. it("reuses the formatted PreToolUse context when the success path throws after formatting", async () => {
  385. const fixture = createExecutorFixture("tool-hook-cap-late-failure");
  386. fixture.registry.register(createTestToolEntry("CapTool", async () => "tool-output"));
  387. const context = "c".repeat(12_000);
  388. const store = createHookArtifactStore();
  389. const executor = createToolExecutor({
  390. artifactStore: store,
  391. // 成功路径格式化 Hook 上下文之后,写结果事件时失败,进入 catch。
  392. emitEvent: async (event) => {
  393. if (event.type === SessionEventType.ToolCallResult) throw new Error("event store down");
  394. },
  395. hookRunner: createInMemoryHookRunner({
  396. hooks: [
  397. {
  398. event: HookEventName.PreToolUse,
  399. matcher: "CapTool",
  400. callback: async (input) => ({
  401. hookSpecificOutput: {
  402. additionalContext: context,
  403. hookEventName: input.hookEventName,
  404. },
  405. }),
  406. },
  407. ],
  408. }),
  409. permissionService: new PermissionService(defaultPermissionConfig),
  410. registry: fixture.registry,
  411. sessionId: fixture.traceContext.sessionId!,
  412. traceContext: fixture.traceContext,
  413. turnId: fixture.traceContext.turnId!,
  414. });
  415. const result = await executor.execute(
  416. { id: createToolCallId("cap-late-failure"), input: {}, name: "CapTool" },
  417. { traceContext: fixture.traceContext },
  418. );
  419. // catch 复用成功路径已过滤、已格式化的结果:只落盘一次,附件指向同一个文件。
  420. expect(result.success).toBe(false);
  421. expect(store.requests).toHaveLength(1);
  422. expect(result.hookAdditionalContexts).toEqual([
  423. expect.stringContaining("Full output saved to: /artifacts/hook-1.txt"),
  424. ]);
  425. });
  426. it("caps the PreToolUse context on the deny path", async () => {
  427. const fixture = createExecutorFixture("tool-hook-cap-deny");
  428. fixture.registry.register(createTestToolEntry("CapTool", async () => "tool-output"));
  429. const context = "b".repeat(10_001);
  430. const result = await fixture
  431. .createExecutor(
  432. createInMemoryHookRunner({
  433. hooks: [
  434. {
  435. event: HookEventName.PreToolUse,
  436. matcher: "CapTool",
  437. callback: async (input) => ({
  438. hookSpecificOutput: {
  439. additionalContext: context,
  440. hookEventName: input.hookEventName,
  441. permissionDecision: "deny",
  442. },
  443. }),
  444. },
  445. ],
  446. }),
  447. )
  448. .execute(
  449. { id: createToolCallId("cap-deny"), input: {}, name: "CapTool" },
  450. { traceContext: fixture.traceContext },
  451. );
  452. expect(result.success).toBe(false);
  453. expect(result.hookAdditionalContexts).toEqual([
  454. `PreToolUse:CapTool hook additional context: ${"b".repeat(10_000)}\n\n` +
  455. "[Hook additionalContext truncated at 10000 chars — persist-to-disk failed: no artifact store]",
  456. ]);
  457. });
  458. });
  459. async function executeWithPostContext(
  460. sessionName: string,
  461. context: string,
  462. artifactStore: ToolArtifactStorePort,
  463. ) {
  464. const fixture = createExecutorFixture(sessionName);
  465. fixture.registry.register(createTestToolEntry("CapTool", async () => "tool-output"));
  466. const hookRunner = createInMemoryHookRunner({
  467. hooks: [
  468. {
  469. event: HookEventName.PostToolUse,
  470. matcher: "CapTool",
  471. callback: async (input) => ({
  472. hookSpecificOutput: { additionalContext: context, hookEventName: input.hookEventName },
  473. }),
  474. },
  475. ],
  476. });
  477. return fixture
  478. .createExecutor(hookRunner, artifactStore)
  479. .execute(
  480. { id: createToolCallId(`${sessionName}-call`), input: {}, name: "CapTool" },
  481. { traceContext: fixture.traceContext },
  482. );
  483. }
  484. function createHookArtifactStore(writeError?: Error) {
  485. const requests: ToolArtifactWriteRequest[] = [];
  486. const store: ToolArtifactStorePort & { requests: ToolArtifactWriteRequest[] } = {
  487. requests,
  488. async writeToolResultArtifact(request) {
  489. if (writeError) throw writeError;
  490. requests.push(request);
  491. return {
  492. bytes: Buffer.byteLength(request.content, "utf8"),
  493. contentType: request.contentType ?? "text/plain",
  494. createdAt: new Date(),
  495. id: `hook-${requests.length}`,
  496. path: `/artifacts/hook-${requests.length}.txt`,
  497. uri: `zcode-artifact://test/hook-${requests.length}`,
  498. };
  499. },
  500. async readToolResultArtifact() {
  501. throw new Error("not used");
  502. },
  503. };
  504. return store;
  505. }
  506. function createExecutorFixture(sessionName: string) {
  507. const sessionId = createSessionId(sessionName);
  508. const turnId = createTurnId("tool-hook-context-turn");
  509. const traceContext = createRootTraceContext({ sessionId, turnId });
  510. const registry = createToolRegistry();
  511. const events: SessionEvent[] = [];
  512. return {
  513. events,
  514. registry,
  515. traceContext,
  516. createExecutor(
  517. hookRunner: ReturnType<typeof createInMemoryHookRunner>,
  518. artifactStore?: ToolArtifactStorePort,
  519. ) {
  520. return createToolExecutor({
  521. artifactStore,
  522. emitEvent: async (event) => {
  523. events.push(event);
  524. },
  525. hookRunner,
  526. permissionService: new PermissionService(defaultPermissionConfig),
  527. registry,
  528. sessionId,
  529. traceContext,
  530. turnId,
  531. });
  532. },
  533. };
  534. }
  535. function createTestToolEntry(name: string, handler: ToolHandler): ToolEntry {
  536. return {
  537. capability: `${name} test capability`,
  538. handler,
  539. inputSchema: {
  540. additionalProperties: true,
  541. type: "object",
  542. },
  543. metadata: {
  544. concurrentSafe: true,
  545. destructive: false,
  546. name,
  547. needsApproval: false,
  548. readOnly: true,
  549. riskLevel: "low",
  550. sideEffectScope: "none",
  551. timeoutMs: 30000,
  552. },
  553. outputSchema: {
  554. type: "string",
  555. },
  556. permission: {
  557. denyPriority: "beforeAsk",
  558. needsApproval: false,
  559. patternSources: ["none"],
  560. permission: "test",
  561. reason: "test tool",
  562. riskLevel: "low",
  563. sideEffectScope: "none",
  564. },
  565. resultBudget: {
  566. maxInlineBytes: 100_000,
  567. maxModelBytes: 100_000,
  568. strategy: "truncate",
  569. },
  570. };
  571. }