tool-search-goal-verification.test.ts 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. import { mkdtemp, rm } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { expect, it } from "vitest";
  5. import { createSessionId, type Model, type ModelRequest } from "@zcode/contracts";
  6. import { createSqliteSessionStore } from "../../adapters/src/storage/session-store/sqlite-session-store.js";
  7. import { toAiSdkMessages } from "../../adapters/src/model/transform.js";
  8. import type { AgentRuntimeInternal } from "../src/runtime/internal.js";
  9. import { collectDiscoveredTools } from "../src/tool/search/history.js";
  10. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  11. import { createTestModelFactory } from "./test-runtime-model.js";
  12. import { createTestSessionEventStore } from "./test-event-store.js";
  13. it("keeps a SQLite goal active when the no-tool verifier rejects completion after a real ToolSearch result", async () => {
  14. const root = await mkdtemp(join(tmpdir(), "zcode-toolsearch-goal-"));
  15. const store = await createSqliteSessionStore({ dbPath: join(root, "session.sqlite") });
  16. const sessionId = createSessionId("toolsearch-goal-verification");
  17. const requests: ModelRequest[] = [];
  18. const baseFactory = createTestModelFactory({
  19. async generateText(request) {
  20. requests.push(request);
  21. // 使用真实 Adapter 投影;协议不配套时会抛错并触发 verifier 的既有 fail-open。
  22. toAiSdkMessages(request.messages, {
  23. providerKind: "anthropic",
  24. toolSearchEnabled: request.toolSearchEnabled,
  25. });
  26. if (requests.length === 1)
  27. return {
  28. text: "",
  29. finishReason: "tool-calls",
  30. usage: {},
  31. toolCalls: [
  32. { id: "search-real", name: "ToolSearch", input: { query: "select:TaskOutput" } },
  33. ],
  34. };
  35. return {
  36. text:
  37. request.tools?.length === 0
  38. ? JSON.stringify({
  39. passed: false,
  40. reason: "Only the tool definition was loaded.",
  41. nextAction: "Read the requested documentation.",
  42. })
  43. : "Work remains.",
  44. finishReason: "stop",
  45. usage: {},
  46. };
  47. },
  48. });
  49. const withSearch = (model: Model): Model => ({
  50. ...model,
  51. requestCapabilities: { toolSearch: { protocolSupported: true, defaultEnabled: true } },
  52. bind: (options) => withSearch(model.bind(options)),
  53. });
  54. const runtime = createTestAgentRuntime(
  55. sessionId,
  56. {
  57. toolSearch: { mode: "native" },
  58. modelStreaming: "off",
  59. titleGeneration: { enabled: false },
  60. workspacePath: root,
  61. },
  62. {
  63. sessionStore: store,
  64. eventStore: createTestSessionEventStore(),
  65. modelFactory: (input) => withSearch(baseFactory(input)),
  66. },
  67. );
  68. try {
  69. await runtime.ensureSessionPersistedForExternalActivity(
  70. "/goal Read the requested documentation",
  71. );
  72. await store.setTarget({ sessionID: sessionId, objective: "Read the requested documentation" });
  73. await runtime.executeTurn("Load the tool definition first.");
  74. await runtime.continueActiveTargetIfIdle({ verifyBeforeContinue: true });
  75. expect((await store.readTarget({ sessionID: sessionId }))?.status).toBe("active");
  76. const verification = requests.find((request) => request.tools?.length === 0);
  77. expect(verification?.toolSearchEnabled).toBe(false);
  78. expect(JSON.stringify(verification?.messages)).not.toContain('"tool_reference"');
  79. expect(JSON.stringify(verification?.messages)).toContain(
  80. "Tool references removed - tool search not enabled",
  81. );
  82. expect(verification?.messages.find((message) => message.role === "tool")).toMatchObject({
  83. toolCallId: "search-real",
  84. });
  85. expect(
  86. collectDiscoveredTools(
  87. (runtime as unknown as AgentRuntimeInternal).messageHistory.borrowReadOnlyRuntimeEntries(),
  88. ),
  89. ).toContain("TaskOutput");
  90. const parts = (await store.messages({ sessionID: sessionId })).flatMap((row) => row.parts);
  91. expect(
  92. parts.find((part) => part.type === "tool" && part.callID === "search-real"),
  93. ).toMatchObject({
  94. state: {
  95. status: "completed",
  96. metadata: { modelContent: [{ type: "tool_reference", toolName: "TaskOutput" }] },
  97. },
  98. });
  99. } finally {
  100. await runtime.closeBrowserSession();
  101. store.close();
  102. await rm(root, { recursive: true, force: true });
  103. }
  104. });