tool-hook-context.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. } from "@zcode/contracts";
  11. import { createInMemoryHookRunner } from "../src/hooks/index.js";
  12. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  13. import { createToolExecutor } from "../src/tool/executor.js";
  14. import { createToolRegistry } from "../src/tool/registry.js";
  15. import type { ToolEntry, ToolHandler } from "../src/tool/types.js";
  16. describe("ToolExecutor hook additional context", () => {
  17. it("adds PreToolUse hook context to successful model content", async () => {
  18. const fixture = createExecutorFixture("tool-hook-pre-context");
  19. fixture.registry.register(createTestToolEntry("ContextTool", async () => "tool-output"));
  20. const hookRunner = createInMemoryHookRunner({
  21. hooks: [
  22. {
  23. event: HookEventName.PreToolUse,
  24. matcher: "ContextTool",
  25. callback: async (input) => ({
  26. hookSpecificOutput: {
  27. additionalContext: "pre-tool context",
  28. hookEventName: input.hookEventName,
  29. },
  30. }),
  31. },
  32. ],
  33. });
  34. const executor = fixture.createExecutor(hookRunner);
  35. const result = await executor.execute(
  36. {
  37. id: createToolCallId("pre-context"),
  38. input: {},
  39. name: "ContextTool",
  40. },
  41. { traceContext: fixture.traceContext },
  42. );
  43. expect(result.success).toBe(true);
  44. expect(result.modelContent).toContain("tool-output");
  45. expect(result.modelContent).toContain("pre-tool context");
  46. });
  47. it("adds PreToolUse and PostToolUseFailure hook context to failed model content", async () => {
  48. const fixture = createExecutorFixture("tool-hook-failure-context");
  49. fixture.registry.register(
  50. createTestToolEntry("FailingContextTool", async () => {
  51. throw new Error("tool exploded");
  52. }),
  53. );
  54. const hookRunner = createInMemoryHookRunner({
  55. hooks: [
  56. {
  57. event: HookEventName.PreToolUse,
  58. matcher: "FailingContextTool",
  59. callback: async (input) => ({
  60. hookSpecificOutput: {
  61. additionalContext: "pre failure context",
  62. hookEventName: input.hookEventName,
  63. },
  64. }),
  65. },
  66. {
  67. event: HookEventName.PostToolUseFailure,
  68. matcher: "FailingContextTool",
  69. callback: async (input) => ({
  70. hookSpecificOutput: {
  71. additionalContext: "post failure context",
  72. hookEventName: input.hookEventName,
  73. },
  74. }),
  75. },
  76. ],
  77. });
  78. const executor = fixture.createExecutor(hookRunner);
  79. const result = await executor.execute(
  80. {
  81. id: createToolCallId("pre-failure-context"),
  82. input: {},
  83. name: "FailingContextTool",
  84. },
  85. { traceContext: fixture.traceContext },
  86. );
  87. expect(result.success).toBe(false);
  88. expect(result.modelContent).toContain("tool exploded");
  89. expect(result.modelContent).toContain("pre failure context");
  90. expect(result.modelContent).toContain("post failure context");
  91. });
  92. it("keeps PreToolUse context when hook-updated input fails schema validation", async () => {
  93. const fixture = createExecutorFixture("tool-hook-invalid-update-context");
  94. let handlerRan = false;
  95. const entry = createTestToolEntry("InvalidHookUpdateTool", async () => {
  96. handlerRan = true;
  97. return "should-not-run";
  98. });
  99. entry.inputSchema = {
  100. additionalProperties: false,
  101. properties: { value: { type: "string" } },
  102. required: ["value"],
  103. type: "object",
  104. };
  105. fixture.registry.register(entry);
  106. const hookRunner = createInMemoryHookRunner({
  107. hooks: [
  108. {
  109. event: HookEventName.PreToolUse,
  110. matcher: "InvalidHookUpdateTool",
  111. callback: async (input) => ({
  112. hookSpecificOutput: {
  113. additionalContext: "invalid update context",
  114. hookEventName: input.hookEventName,
  115. updatedInput: {},
  116. },
  117. }),
  118. },
  119. ],
  120. });
  121. const result = await fixture.createExecutor(hookRunner).execute(
  122. {
  123. id: createToolCallId("invalid-hook-update-context"),
  124. input: { value: "valid-before-hook" },
  125. name: "InvalidHookUpdateTool",
  126. },
  127. { traceContext: fixture.traceContext },
  128. );
  129. expect(result.success).toBe(false);
  130. expect(result.error?.message).toContain("Tool input failed inputSchema validation");
  131. expect(result.modelContent).toContain("invalid update context");
  132. expect(result.modelContent).not.toContain("InputValidationError:");
  133. expect(handlerRan).toBe(false);
  134. });
  135. it("routes a handler failure through the existing failure lifecycle", async () => {
  136. const fixture = createExecutorFixture("tool-handler-failure");
  137. let handlerCalls = 0;
  138. let postSuccessRan = false;
  139. let postFailureRan = false;
  140. fixture.registry.register(
  141. createTestToolEntry("HandlerFailureTool", async () => {
  142. handlerCalls += 1;
  143. return {
  144. result: false,
  145. errorCode: 7,
  146. message: "Tool-specific failure",
  147. };
  148. }),
  149. );
  150. const hookRunner = createInMemoryHookRunner({
  151. hooks: [
  152. {
  153. event: HookEventName.PreToolUse,
  154. matcher: "HandlerFailureTool",
  155. callback: async (input) => ({
  156. hookSpecificOutput: {
  157. additionalContext: "pre failure context",
  158. hookEventName: input.hookEventName,
  159. },
  160. }),
  161. },
  162. {
  163. event: HookEventName.PostToolUse,
  164. matcher: "HandlerFailureTool",
  165. callback: async () => {
  166. postSuccessRan = true;
  167. return {};
  168. },
  169. },
  170. {
  171. event: HookEventName.PostToolUseFailure,
  172. matcher: "HandlerFailureTool",
  173. callback: async (input) => {
  174. postFailureRan = true;
  175. return {
  176. hookSpecificOutput: {
  177. additionalContext: "post failure context",
  178. hookEventName: input.hookEventName,
  179. },
  180. };
  181. },
  182. },
  183. ],
  184. });
  185. const result = await fixture.createExecutor(hookRunner).execute(
  186. {
  187. id: createToolCallId("handler-failure"),
  188. input: {},
  189. name: "HandlerFailureTool",
  190. },
  191. { traceContext: fixture.traceContext },
  192. );
  193. expect(result.success).toBe(false);
  194. expect(result.error).toMatchObject({
  195. code: "7",
  196. message: "Tool-specific failure",
  197. });
  198. expect(result.modelContent).toContain("<tool_use_error>Tool-specific failure</tool_use_error>");
  199. expect(result.modelContent).toContain("pre failure context");
  200. expect(result.modelContent).toContain("post failure context");
  201. expect(handlerCalls).toBe(1);
  202. expect(postSuccessRan).toBe(false);
  203. expect(postFailureRan).toBe(true);
  204. expect(fixture.events.map((event) => event.type)).toEqual([
  205. SessionEventType.ToolCallStarted,
  206. SessionEventType.ToolCallError,
  207. ]);
  208. });
  209. it("records non-blocking PostToolUse continue false without failing the tool", async () => {
  210. const fixture = createExecutorFixture("tool-hook-post-continue-false");
  211. const events: SessionEvent[] = [];
  212. let handlerRan = false;
  213. fixture.registry.register(
  214. createTestToolEntry("PostContinueTool", async () => {
  215. handlerRan = true;
  216. return "tool-output";
  217. }),
  218. );
  219. const hookRunner = createInMemoryHookRunner({
  220. emitEvent: async (event) => {
  221. events.push(event);
  222. },
  223. hooks: [
  224. {
  225. event: HookEventName.PostToolUse,
  226. matcher: "PostContinueTool",
  227. callback: async (input) => ({
  228. continue: false,
  229. reason: "post hook requested stop",
  230. hookSpecificOutput: {
  231. hookEventName: input.hookEventName,
  232. },
  233. }),
  234. },
  235. ],
  236. });
  237. const executor = fixture.createExecutor(hookRunner);
  238. const result = await executor.execute(
  239. {
  240. id: createToolCallId("post-continue-false"),
  241. input: {},
  242. name: "PostContinueTool",
  243. },
  244. { traceContext: fixture.traceContext },
  245. );
  246. expect(result.success).toBe(true);
  247. expect(handlerRan).toBe(true);
  248. expect(events.map((event) => event.type)).toEqual([
  249. // D20:block 决策只产生一个终态事件(runner.ts:143 为 blocked ? Blocked : Completed)。
  250. // 此前同时断言 Completed + Blocked,会让「被拦截」在 UI 上呈现为已完成绿勾。
  251. SessionEventType.HookRunStarted,
  252. SessionEventType.HookRunBlocked,
  253. ]);
  254. });
  255. it("matches Task hook matcher aliases without rewriting the Agent hook input", async () => {
  256. const fixture = createExecutorFixture("tool-hook-task-agent-alias");
  257. fixture.registry.register(createTestToolEntry("Agent", async () => "agent-output"));
  258. let observedToolName: string | undefined;
  259. const hookRunner = createInMemoryHookRunner({
  260. hooks: [
  261. {
  262. event: HookEventName.PreToolUse,
  263. matcher: "Task",
  264. callback: async (input) => {
  265. observedToolName = "toolName" in input ? input.toolName : undefined;
  266. return {
  267. hookSpecificOutput: {
  268. additionalContext: "task matcher matched agent",
  269. hookEventName: input.hookEventName,
  270. },
  271. };
  272. },
  273. },
  274. ],
  275. });
  276. const executor = fixture.createExecutor(hookRunner);
  277. const result = await executor.execute(
  278. {
  279. id: createToolCallId("agent-task-matcher"),
  280. input: {},
  281. name: "Agent",
  282. },
  283. { traceContext: fixture.traceContext },
  284. );
  285. expect(result.success).toBe(true);
  286. expect(result.modelContent).toContain("task matcher matched agent");
  287. expect(observedToolName).toBe("Agent");
  288. });
  289. it("matches Agent hook matcher aliases without rewriting the Task hook input", async () => {
  290. const fixture = createExecutorFixture("tool-hook-agent-task-alias");
  291. fixture.registry.register(createTestToolEntry("Task", async () => "task-output"));
  292. let observedToolName: string | undefined;
  293. const hookRunner = createInMemoryHookRunner({
  294. hooks: [
  295. {
  296. event: HookEventName.PreToolUse,
  297. matcher: "Agent",
  298. callback: async (input) => {
  299. observedToolName = "toolName" in input ? input.toolName : undefined;
  300. return {
  301. hookSpecificOutput: {
  302. additionalContext: "agent matcher matched task",
  303. hookEventName: input.hookEventName,
  304. },
  305. };
  306. },
  307. },
  308. ],
  309. });
  310. const executor = fixture.createExecutor(hookRunner);
  311. const result = await executor.execute(
  312. {
  313. id: createToolCallId("task-agent-matcher"),
  314. input: {},
  315. name: "Task",
  316. },
  317. { traceContext: fixture.traceContext },
  318. );
  319. expect(result.success).toBe(true);
  320. expect(result.modelContent).toContain("agent matcher matched task");
  321. expect(observedToolName).toBe("Task");
  322. });
  323. });
  324. function createExecutorFixture(sessionName: string) {
  325. const sessionId = createSessionId(sessionName);
  326. const turnId = createTurnId("tool-hook-context-turn");
  327. const traceContext = createRootTraceContext({ sessionId, turnId });
  328. const registry = createToolRegistry();
  329. const events: SessionEvent[] = [];
  330. return {
  331. events,
  332. registry,
  333. traceContext,
  334. createExecutor(hookRunner: ReturnType<typeof createInMemoryHookRunner>) {
  335. return createToolExecutor({
  336. emitEvent: async (event) => {
  337. events.push(event);
  338. },
  339. hookRunner,
  340. permissionService: new PermissionService(defaultPermissionConfig),
  341. registry,
  342. sessionId,
  343. traceContext,
  344. turnId,
  345. });
  346. },
  347. };
  348. }
  349. function createTestToolEntry(name: string, handler: ToolHandler): ToolEntry {
  350. return {
  351. capability: `${name} test capability`,
  352. handler,
  353. inputSchema: {
  354. additionalProperties: true,
  355. type: "object",
  356. },
  357. metadata: {
  358. concurrentSafe: true,
  359. destructive: false,
  360. name,
  361. needsApproval: false,
  362. readOnly: true,
  363. riskLevel: "low",
  364. sideEffectScope: "none",
  365. timeoutMs: 30000,
  366. },
  367. outputSchema: {
  368. type: "string",
  369. },
  370. permission: {
  371. denyPriority: "beforeAsk",
  372. needsApproval: false,
  373. patternSources: ["none"],
  374. permission: "test",
  375. reason: "test tool",
  376. riskLevel: "low",
  377. sideEffectScope: "none",
  378. },
  379. resultBudget: {
  380. maxInlineBytes: 100_000,
  381. maxModelBytes: 100_000,
  382. strategy: "truncate",
  383. },
  384. };
  385. }