tool-search-local.test.ts 17 KB

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