tool-search-local.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. createSessionId,
  4. createTurnId,
  5. DeferredToolCallInputSchema,
  6. TodoWriteInputSchema,
  7. type ToolSearchExecutionContext,
  8. } from "@zcode/contracts";
  9. import type { RuntimeMessageEntry } from "../src/agent/message-history.js";
  10. import { buildToolExposure } from "../src/tool/search/exposure.js";
  11. import { createToolRegistry } from "../src/tool/registry.js";
  12. import { deferredToolCallEntry } from "../src/tool/handlers/deferred-tool-call.js";
  13. import { toolSearchToolEntry } from "../src/tool/handlers/tool-search.js";
  14. import { createToolExecutor } from "../src/tool/executor.js";
  15. import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
  16. import type { ToolEntry } from "../src/tool/types.js";
  17. import { createTestRuntimeModel } from "./test-runtime-model.js";
  18. import { createInMemoryHookRunner } from "../src/hooks/index.js";
  19. import type { ToolExecutorOptions } from "../src/tool/executor/types.js";
  20. import { resolveDeferredToolCall } from "../src/tool/deferred-call.js";
  21. function fixture(
  22. overrides: Partial<ToolEntry> = {},
  23. executorOptions: Partial<ToolExecutorOptions> = {},
  24. ) {
  25. const registry = createToolRegistry();
  26. const handler = vi.fn(async (input: unknown) => input);
  27. const target: ToolEntry = {
  28. ...toolSearchToolEntry,
  29. metadata: {
  30. ...toolSearchToolEntry.metadata,
  31. name: "DeferredA",
  32. description: "A",
  33. shouldDefer: true,
  34. },
  35. inputSchema: {
  36. type: "object",
  37. properties: { value: { type: "number" } },
  38. required: ["value"],
  39. additionalProperties: false,
  40. },
  41. runtimeInputSchema: undefined,
  42. outputSchema: {},
  43. runtimeOutputSchema: undefined,
  44. formatModelContent: undefined,
  45. permission: undefined,
  46. handler,
  47. ...overrides,
  48. };
  49. registry.register(toolSearchToolEntry);
  50. registry.register(deferredToolCallEntry);
  51. registry.register(target);
  52. registry.register({
  53. ...target,
  54. metadata: { ...target.metadata, name: "DeferredB", description: "B" },
  55. });
  56. registry.register({
  57. ...target,
  58. metadata: { ...target.metadata, name: "Resident", shouldDefer: false },
  59. });
  60. const model = createTestRuntimeModel({
  61. generateText: async () => ({ text: "", finishReason: "stop", usage: {} }),
  62. });
  63. const expose = (entries: RuntimeMessageEntry[] = []) =>
  64. buildToolExposure({ model, mode: "local", tools: registry.toContracts(), registry, entries });
  65. const executor = createToolExecutor({
  66. registry,
  67. emitEvent: async () => {},
  68. permissionService: new PermissionService(defaultPermissionConfig),
  69. sessionId: createSessionId("local-search"),
  70. turnId: createTurnId("turn"),
  71. getMode: () => "yolo",
  72. ...executorOptions,
  73. });
  74. return { registry, target, handler, model, expose, executor };
  75. }
  76. function resultEntry(content: RuntimeMessageEntry["message"]["content"]): RuntimeMessageEntry {
  77. return { message: { role: "tool", toolName: "ToolSearch", toolCallId: "search", content } };
  78. }
  79. const reference = (toolName: string) => ({ type: "tool_reference" as const, toolName });
  80. const text = (value: unknown) => JSON.stringify(value);
  81. describe("Local ToolSearch request projection", () => {
  82. it("exposes one concise calling example that satisfies both wrapper and target schemas", () => {
  83. const { expose } = fixture();
  84. const description = expose().tools.find((tool) => tool.name === "ToolSearch")!.description!;
  85. expect(description).toMatch(/^Fetches .* called using DeferredToolCall\./);
  86. expect(description).toContain("Call resident tools directly using their normal tool calls");
  87. expect(description).toContain(
  88. "For deferred tools, parameters describes the input object passed to DeferredToolCall.",
  89. );
  90. expect(description).not.toContain("does not change a tool's classification");
  91. expect(description).not.toContain("the same encoding");
  92. expect(description).not.toContain("<commentary>");
  93. const examples = [...description.matchAll(/<example>([\s\S]*?)<\/example>/g)];
  94. expect(examples).toHaveLength(1);
  95. const json = examples[0]![1]!.match(/DeferredToolCall\(([^\n]+)\)/)?.[1];
  96. const call = DeferredToolCallInputSchema.parse(JSON.parse(json!));
  97. expect(call.name).toBe("TodoWrite");
  98. expect(TodoWriteInputSchema.parse(call.input)).toEqual(call.input);
  99. });
  100. it("expands a reference run in one functions block without changing tools or raw history", () => {
  101. const { expose } = fixture();
  102. const entries = [resultEntry([reference("DeferredA"), reference("DeferredB")])];
  103. const original = structuredClone(entries);
  104. const initial = expose();
  105. const searched = expose(entries);
  106. expect(initial.tools.map((tool) => tool.name)).toEqual([
  107. "ToolSearch",
  108. "DeferredToolCall",
  109. "Resident",
  110. ]);
  111. expect(searched.tools).toEqual(initial.tools);
  112. const content = text(searched.entries[0]?.message.content);
  113. expect(content.match(/<functions>/g)).toHaveLength(1);
  114. expect(content.match(/<function>/g)).toHaveLength(2);
  115. expect(content).toContain("parameters");
  116. expect(content).not.toContain("tool_reference");
  117. expect(searched.tools.some((tool) => tool.deferLoading)).toBe(false);
  118. expect(entries).toEqual(original);
  119. expect([...searched.context.discovered]).toEqual(["DeferredA", "DeferredB"]);
  120. });
  121. it("keeps intervening text and separate results in order and removes unavailable references", () => {
  122. const { expose } = fixture();
  123. const entries = [
  124. resultEntry([
  125. reference("DeferredA"),
  126. { type: "text" as const, text: "HOOK" },
  127. reference("missing"),
  128. reference("DeferredB"),
  129. ]),
  130. resultEntry([reference("DeferredA")]),
  131. ];
  132. const projected = expose(entries).entries;
  133. const content = text(projected[0]?.message.content);
  134. expect(content.match(/<functions>/g)).toHaveLength(2);
  135. expect(content.indexOf("DeferredA")).toBeLessThan(content.indexOf("HOOK"));
  136. expect(content.indexOf("HOOK")).toBeLessThan(content.indexOf("DeferredB"));
  137. expect(content).not.toContain("missing");
  138. expect(text(projected[1]?.message.content).match(/<functions>/g)).toHaveLength(1);
  139. expect(text(expose([resultEntry([reference("missing")])]).entries)).toContain(
  140. "tools no longer available",
  141. );
  142. });
  143. it("returns the active Local definition when directly selecting a resident control", () => {
  144. const { expose } = fixture();
  145. const result = expose([resultEntry([reference("ToolSearch")])]);
  146. const content = result.entries[0]!.message.content;
  147. if (!Array.isArray(content) || content[0]?.type !== "text")
  148. throw new Error("Expected expanded definition");
  149. const definition = JSON.parse(
  150. content[0].text.split("\n")[1]!.slice("<function>".length, -"</function>".length),
  151. );
  152. expect(definition.description).toBe(
  153. result.tools.find((tool) => tool.name === "ToolSearch")?.description,
  154. );
  155. });
  156. it("promotes checkpoint definitions into ordinary tools without synthetic results", () => {
  157. const { expose } = fixture();
  158. const entries: RuntimeMessageEntry[] = [
  159. {
  160. message: { role: "user", content: "summary" },
  161. metadata: {
  162. compactBoundary: { boundaryId: "boundary", preCompactDiscoveredTools: ["DeferredA"] },
  163. },
  164. },
  165. ];
  166. const result = expose(entries);
  167. expect([...result.context.discovered]).toEqual(["DeferredA"]);
  168. expect(text(result.entries)).not.toContain("<functions>");
  169. expect(result.tools.find((tool) => tool.name === "DeferredA")).toMatchObject({
  170. name: "DeferredA",
  171. });
  172. expect(result.tools.find((tool) => tool.name === "DeferredA")?.deferLoading).toBeUndefined();
  173. });
  174. });
  175. describe("DeferredToolCall execution", () => {
  176. it("normalizes once and isolates nested handler mutations from the model input", async () => {
  177. const { registry, expose, executor } = fixture({
  178. inputSchema: { type: "object" },
  179. handler: async (input) => {
  180. (input as { nested: { values: number[] } }).nested.values.push(2);
  181. return input;
  182. },
  183. });
  184. const raw = {
  185. id: "isolated",
  186. name: "DeferredToolCall",
  187. input: { name: "DeferredA", input: { nested: { values: [1] } } },
  188. };
  189. const context = expose().context;
  190. const admitted = resolveDeferredToolCall(raw, context, registry).call;
  191. expect(admitted).toEqual({
  192. id: raw.id,
  193. name: "DeferredA",
  194. input: raw.input.input,
  195. modelCallWrapper: "DeferredToolCall",
  196. });
  197. expect(resolveDeferredToolCall(admitted, context, registry).call).toBe(admitted);
  198. const result = await executor.execute(admitted, { toolSearch: context });
  199. expect(result.success).toBe(true);
  200. expect(raw.input.input.nested.values).toEqual([1]);
  201. expect(admitted.input).toEqual(raw.input.input);
  202. });
  203. it.each(["allow", "deny"] as const)(
  204. "uses target approval and terminal behavior: %s",
  205. async (decision) => {
  206. const permission = vi.fn(async () => ({ decision }));
  207. const { executor, expose, handler } = fixture(
  208. {
  209. metadata: {
  210. ...toolSearchToolEntry.metadata,
  211. name: "DeferredA",
  212. shouldDefer: true,
  213. readOnly: false,
  214. concurrentSafe: false,
  215. needsApproval: true,
  216. sideEffectScope: "workspace",
  217. riskLevel: "medium",
  218. stopTurnOnSuccess: true,
  219. },
  220. },
  221. { getMode: () => "default", permissionBroker: { requestPermission: permission } },
  222. );
  223. for (const wrapped of [false, true]) {
  224. const result = await executor.execute(
  225. {
  226. id: "approval",
  227. name: wrapped ? "DeferredToolCall" : "DeferredA",
  228. input: wrapped ? { name: "DeferredA", input: { value: 1 } } : { value: 1 },
  229. },
  230. { toolSearch: expose().context },
  231. );
  232. expect(result.success).toBe(decision === "allow");
  233. expect(result.turnControl?.stopTurnAfterResult).toBe(
  234. decision === "allow" ? true : undefined,
  235. );
  236. }
  237. expect(permission).toHaveBeenCalledTimes(2);
  238. for (const [request] of permission.mock.calls)
  239. expect(request).toMatchObject({ toolName: "DeferredA" });
  240. expect(handler).toHaveBeenCalledTimes(decision === "allow" ? 2 : 0);
  241. },
  242. );
  243. it.each([
  244. null,
  245. [],
  246. { name: "DeferredA", input: "{}" },
  247. { name: "DeferredA", input: [] },
  248. { name: "DeferredA", input: {}, id: "nested" },
  249. { name: "DeferredA" },
  250. ])("rejects malformed wrapper input before target hooks: %j", async (input) => {
  251. const hook = vi.fn(async () => ({}));
  252. const { executor, expose, handler } = fixture(
  253. {},
  254. {
  255. hookRunner: createInMemoryHookRunner({
  256. hooks: [{ event: "PreToolUse", matcher: "DeferredA", callback: hook }],
  257. }),
  258. },
  259. );
  260. const result = await executor.execute(
  261. { id: "malformed", name: "DeferredToolCall", input },
  262. { toolSearch: expose().context },
  263. );
  264. expect(result.success).toBe(false);
  265. expect(result.modelContent).toContain("InputValidationError");
  266. expect(handler).not.toHaveBeenCalled();
  267. expect(hook).not.toHaveBeenCalled();
  268. });
  269. it("uses the target for hooks, media, handler errors and cancellation", async () => {
  270. const callback = vi.fn(async (input) => ({
  271. hookSpecificOutput: { hookEventName: input.hookEventName, additionalContext: "TARGET_HOOK" },
  272. }));
  273. const { executor, expose, handler } = fixture(
  274. {
  275. formatModelContent: () => [
  276. { type: "text", text: "target output" },
  277. { type: "image", data: "aGVsbG8=", mimeType: "image/png" },
  278. ],
  279. },
  280. {
  281. hookRunner: createInMemoryHookRunner({
  282. hooks: [{ event: "PostToolUse", matcher: "DeferredA", callback }],
  283. }),
  284. },
  285. );
  286. const execute = (wrapped: boolean, signal?: AbortSignal) =>
  287. executor.execute(
  288. {
  289. id: "same",
  290. name: wrapped ? "DeferredToolCall" : "DeferredA",
  291. input: wrapped ? { name: "DeferredA", input: { value: 1 } } : { value: 1 },
  292. },
  293. { toolSearch: expose().context, signal },
  294. );
  295. const direct = await execute(false);
  296. const wrapped = await execute(true);
  297. expect(wrapped.modelContent).toEqual(direct.modelContent);
  298. expect(JSON.stringify(wrapped.modelContent)).toContain("TARGET_HOOK");
  299. expect(callback).toHaveBeenCalledTimes(2);
  300. expect(handler).toHaveBeenCalledTimes(2);
  301. const cancelled = await execute(true, AbortSignal.abort());
  302. expect(cancelled.success).toBe(false);
  303. expect(handler).toHaveBeenCalledTimes(2);
  304. handler.mockRejectedValueOnce(new Error("target failed"));
  305. const failedDirect = await execute(false);
  306. handler.mockRejectedValueOnce(new Error("target failed"));
  307. const failedWrapped = await execute(true);
  308. expect(failedWrapped.error?.message).toEqual(failedDirect.error?.message);
  309. expect(failedWrapped.modelContent).toEqual(failedDirect.modelContent);
  310. });
  311. it("rejects provider-native targets and follows current deferred classification", async () => {
  312. const { registry, target, expose, executor, handler } = fixture();
  313. registry.register(
  314. { ...target, providerNative: { type: "test" } as never },
  315. { silentDuplicateWarning: true },
  316. );
  317. const call = {
  318. id: "classification",
  319. name: "DeferredToolCall",
  320. input: { name: "DeferredA", input: { value: 1 } },
  321. };
  322. expect((await executor.execute(call, { toolSearch: expose().context })).success).toBe(false);
  323. expect(handler).not.toHaveBeenCalled();
  324. registry.register(target, { silentDuplicateWarning: true });
  325. expect((await executor.execute(call, { toolSearch: expose().context })).success).toBe(true);
  326. registry.register(
  327. { ...target, metadata: { ...target.metadata, alwaysLoad: true } },
  328. { silentDuplicateWarning: true },
  329. );
  330. expect((await executor.execute(call, { toolSearch: expose().context })).success).toBe(false);
  331. expect(handler).toHaveBeenCalledTimes(1);
  332. });
  333. it("uses the ordinary target execution and error formatting with the original call ID", async () => {
  334. const { executor, expose, handler } = fixture();
  335. const toolSearch = expose().context;
  336. const wrapped = await executor.execute(
  337. {
  338. id: "wrapped",
  339. name: "DeferredToolCall",
  340. input: { name: "DeferredA", input: { value: 7 } },
  341. },
  342. { toolSearch },
  343. );
  344. expect(wrapped).toMatchObject({ success: true, toolCallId: "wrapped", toolName: "DeferredA" });
  345. expect(handler).toHaveBeenCalledExactlyOnceWith(
  346. { value: 7 },
  347. expect.objectContaining({ toolCallId: "wrapped" }),
  348. );
  349. const directError = await executor.execute(
  350. { id: "direct-error", name: "DeferredA", input: {} },
  351. { toolSearch },
  352. );
  353. const wrappedError = await executor.execute(
  354. { id: "wrapped-error", name: "DeferredToolCall", input: { name: "DeferredA", input: {} } },
  355. { toolSearch },
  356. );
  357. expect(wrappedError.modelContent).toEqual(directError.modelContent);
  358. expect(wrappedError.error?.type).toEqual(directError.error?.type);
  359. });
  360. it.each(["Resident", "ToolSearch", "DeferredToolCall", "missing"])(
  361. "rejects %s before target execution",
  362. async (name) => {
  363. const { executor, expose, handler } = fixture();
  364. const result = await executor.execute(
  365. { id: "rejected", name: "DeferredToolCall", input: { name, input: { value: 1 } } },
  366. { toolSearch: expose().context },
  367. );
  368. expect(result).toMatchObject({
  369. success: false,
  370. toolCallId: "rejected",
  371. toolName: "DeferredToolCall",
  372. });
  373. if (name === "Resident") expect(result.error?.message).toContain("directly");
  374. expect(handler).not.toHaveBeenCalled();
  375. },
  376. );
  377. it("rejects disabled, native, excluded and currently always-loaded targets", async () => {
  378. const { executor, expose, handler, registry, target } = fixture();
  379. const context = expose().context;
  380. const contexts: ToolSearchExecutionContext[] = [
  381. { ...context, mode: "off", enabled: false },
  382. { ...context, mode: "native" },
  383. { ...context, catalog: [] },
  384. ];
  385. registry.register(
  386. { ...target, metadata: { ...target.metadata, alwaysLoad: true } },
  387. { silentDuplicateWarning: true },
  388. );
  389. contexts.push(expose().context);
  390. for (const toolSearch of contexts) {
  391. const result = await executor.execute(
  392. {
  393. id: "rejected",
  394. name: "DeferredToolCall",
  395. input: { name: "DeferredA", input: { value: 1 } },
  396. },
  397. { toolSearch },
  398. );
  399. expect(result.success).toBe(false);
  400. }
  401. expect(handler).not.toHaveBeenCalled();
  402. });
  403. });