tool-search-local.test.ts 19 KB

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