tools.test.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. import { describe, expect, it, vi } from "vitest";
  2. import { createToolRegistry, registerBuiltInTools } from "../../src/tool/index.js";
  3. import { isDynamicWorkflowToolName } from "../../src/tool/handlers/index.js";
  4. import {
  5. sessionControlTools,
  6. sessionControlToolsByKind,
  7. } from "../../src/tool/session-control/index.js";
  8. import { sessionControlForRuntime } from "../../src/tool/session-control/contract.js";
  9. import { buildToolExposure, buildToolSearchAnnouncement } from "../../src/tool/search/exposure.js";
  10. import { createTestRuntimeModel } from "../test-runtime-model.js";
  11. import type { ToolExecutionContext } from "../../src/tool/types.js";
  12. import type { AppSessionControl, CliSessionControl } from "@zcode/session-control/contracts";
  13. const rootSession = { kind: "cli" as const, workspacePath: "/workspace", sessionId: "caller" };
  14. const target = { ...rootSession, sessionId: "sess_target" };
  15. function context(control: Partial<CliSessionControl>): ToolExecutionContext {
  16. return {
  17. toolCallId: "tool-1",
  18. traceId: "trace-1" as never,
  19. sessionId: "caller" as never,
  20. runtimeScope: "main",
  21. abortSignal: new AbortController().signal,
  22. workingDirectory: "/workspace",
  23. workspaceRoot: "/workspace",
  24. sessionControl: {
  25. kind: "cli",
  26. control: control as CliSessionControl,
  27. context: () => ({ callerId: "trusted-caller", rootSession, allowedScopes: [rootSession] }),
  28. },
  29. };
  30. }
  31. const entry = (name: string, kind: "cli" | "app" = "cli") =>
  32. sessionControlToolsByKind[kind].find((tool) => tool.metadata.name === name)!;
  33. const SHARED = [
  34. "ListSessions",
  35. "ReadSession",
  36. "CreateSession",
  37. "ForkSession",
  38. "SendToSession",
  39. "WaitSessions",
  40. "InterruptSession",
  41. "RenameSession",
  42. ];
  43. const APP_ONLY = ["ListProjects", "OpenSession", "SetSessionArchived", "SetSessionPinned"];
  44. /** 受动态工作流灰度门管的工具里,ListModels 之外的那十个。 */
  45. const DYNAMIC_WORKFLOW_ONLY = [
  46. "CreateWorkflow",
  47. "AmendWorkflow",
  48. "SaveWorkflow",
  49. "ListSavedWorkflows",
  50. "EvalWorkflowSnippet",
  51. "ListWorkflowRuns",
  52. "GetWorkflowRun",
  53. "ResumeWorkflowRun",
  54. "ResolveWorkflowQuestion",
  55. "FillWorkflowHole",
  56. ];
  57. describe("session control production tools", () => {
  58. it.each(["cli", "app"] as const)("advertises the %s surface under shared names", (kind) => {
  59. const registry = createToolRegistry();
  60. registerBuiltInTools(registry, { sessionControlKind: kind });
  61. const model = createTestRuntimeModel({
  62. generateText: async () => ({ text: "", finishReason: "stop" }),
  63. });
  64. const input = {
  65. registry,
  66. model,
  67. tools: registry.toContracts(),
  68. entries: [],
  69. mode: "local" as const,
  70. };
  71. const exposure = buildToolExposure(input);
  72. const names = new Set([...SHARED, ...APP_ONLY]);
  73. const controls = exposure.context.catalog.filter((tool) => names.has(tool.name));
  74. expect(controls.map((tool) => tool.name).sort()).toEqual(
  75. [...SHARED, ...(kind === "cli" ? [] : APP_ONLY)].sort(),
  76. );
  77. expect(controls.every((tool) => tool.deferred && tool.searchHint)).toBe(true);
  78. expect(exposure.tools.some((tool) => names.has(tool.name))).toBe(false);
  79. const announcement = buildToolSearchAnnouncement(input);
  80. expect(announcement?.metadata?.toolSearchAnnouncement?.addedNames).toEqual(
  81. expect.arrayContaining(controls.map((tool) => tool.name)),
  82. );
  83. });
  84. it("registers the variant chosen by the trusted launch binding, with no fallback", () => {
  85. for (const mode of [undefined, "cli", "app"] as const) {
  86. const registry = createToolRegistry();
  87. registerBuiltInTools(registry, { sessionControlKind: mode });
  88. expect(sessionControlTools.filter((tool) => registry.has(tool.metadata.name))).toHaveLength(
  89. mode === "cli" ? 8 : mode === "app" ? 12 : 0,
  90. );
  91. expect(registry.has("OpenSession")).toBe(mode === "app");
  92. if (mode) expect(registry.get("CreateSession")).toBe(entry("CreateSession", mode));
  93. }
  94. // App 是独立 CLI 的父集:共有工具同名,App 版只多出自己的参数。
  95. expect(sessionControlToolsByKind.cli.map((tool) => tool.metadata.name)).toEqual(SHARED);
  96. expect(sessionControlToolsByKind.app.map((tool) => tool.metadata.name)).toEqual([
  97. ...SHARED,
  98. ...APP_ONLY,
  99. ]);
  100. // 规格 0.14:CLI 的 cwd 已删除(唯一合法值是绑定 workspace,工具自己已知);
  101. // App 的 project 保留,因为 ListProjects 是它现成的发现链。
  102. expect(entry("CreateSession", "cli").inputSchema.required).toEqual(["prompt"]);
  103. expect(entry("CreateSession", "app").inputSchema.required).toContain("project");
  104. });
  105. /**
  106. * 规格 0.15:ListModels 有消费者才注册,且不计入冷恢复判据。
  107. *
  108. * 它的两个消费者是 CreateWorkflow(灰度开启)与 CreateSession(会话控制在场)。0.14 无条件注册,
  109. * 于是「灰度关 + 无会话控制」的会话(例如子代理)也有它,描述却叫模型去填两个不存在的工具。
  110. */
  111. it("registers ListModels only where one of its consumers exists", () => {
  112. for (const [options, registered] of [
  113. [{ sessionControlKind: "cli" as const, includeDynamicWorkflow: false }, true],
  114. [{ sessionControlKind: "app" as const, includeDynamicWorkflow: false }, true],
  115. [{ includeDynamicWorkflow: true }, true],
  116. [{}, true],
  117. [{ includeDynamicWorkflow: false }, false],
  118. ] as const) {
  119. const registry = createToolRegistry();
  120. registerBuiltInTools(registry, options);
  121. expect({ options, registered: registry.has("ListModels") }).toEqual({ options, registered });
  122. }
  123. // 会话控制在场时灰度关闭也照常注册,另外十个工作流工具仍随灰度下架。
  124. const sessionOnly = createToolRegistry();
  125. registerBuiltInTools(sessionOnly, { sessionControlKind: "cli", includeDynamicWorkflow: false });
  126. expect(DYNAMIC_WORKFLOW_ONLY.filter((name) => sessionOnly.has(name))).toEqual([]);
  127. // 冷恢复判据:只为挑模型调过一次 ListModels,不说明会话用过工作流。
  128. expect(isDynamicWorkflowToolName("ListModels")).toBe(false);
  129. });
  130. /**
  131. * 规格 0.14:模型可见文案不得指向已从工具面删除的参数。
  132. *
  133. * 这一条是审出来的真实缺陷:`requestId` 退出工具面后,公共指令仍写着 "Reuse requestId",
  134. * 而 strictObject 会拒绝它——模型照字面做就卡死,改为省略身份则拿到新的 toolCallId,
  135. * 于是重复建会话或重复发消息。描述与 schema 必须同源校验,不能靠人读。
  136. */
  137. it("never names a parameter the tool surface does not accept", () => {
  138. // 这几个参数是**直接删除**的(规格 0.14),没有替代写法,所以模型可见文案里出现任何一次
  139. // 都是错的。`requestId` 不在此列:它仍是回执字段,重试指令要指着它说「从结果里取」,
  140. // 那层语义正则判不了,由下面一条单独断言。
  141. const deleted = ["cwd", "uiTarget", "host"];
  142. for (const kind of ["cli", "app"] as const)
  143. for (const tool of sessionControlToolsByKind[kind]) {
  144. const text = [
  145. tool.metadata.description,
  146. tool.metadata.searchHint,
  147. ...(tool.metadata.modelInstructions ?? []),
  148. ].join(" ");
  149. expect({
  150. tool: `${kind}:${tool.metadata.name}`,
  151. named: deleted.filter((name) => new RegExp(`\\b${name}\\b`).test(text)),
  152. }).toEqual({ tool: `${kind}:${tool.metadata.name}`, named: [] });
  153. }
  154. });
  155. /**
  156. * 规格 0.14:`requestId` 退出工具面后,公共指令仍写着 "Reuse requestId"——strictObject 会拒绝它,
  157. * 模型照字面做就卡死;改为省略身份重新调用则拿到新的 toolCallId,于是重复建会话或重复发消息。
  158. * 所以提到 requestId 的唯一合法语境是「从回执取值,作为 retryOf 传回」,且必须写明没有
  159. * requestId 输入字段;而这条指令只能出现在真正收 retryOf 的写工具上。
  160. */
  161. it("only mentions requestId as a value to replay through retryOf", () => {
  162. for (const kind of ["cli", "app"] as const)
  163. for (const tool of sessionControlToolsByKind[kind]) {
  164. const properties = tool.inputSchema.properties ?? {};
  165. expect(properties, `${kind}:${tool.metadata.name}`).not.toHaveProperty("requestId");
  166. const text = [
  167. tool.metadata.description,
  168. tool.metadata.searchHint,
  169. ...(tool.metadata.modelInstructions ?? []),
  170. ].join(" ");
  171. const retryable = "retryOf" in properties;
  172. expect({ tool: tool.metadata.name, mentions: /\brequestId\b/.test(text) }).toEqual({
  173. tool: tool.metadata.name,
  174. mentions: retryable,
  175. });
  176. if (!retryable) continue;
  177. expect(tool.inputSchema.required ?? [], tool.metadata.name).not.toContain("retryOf");
  178. expect(
  179. text,
  180. `${kind}:${tool.metadata.name} 没说清 requestId 要作为 retryOf 回放`,
  181. ).toContain("`retryOf`");
  182. expect(text, `${kind}:${tool.metadata.name} 没说明没有 requestId 输入字段`).toContain(
  183. "no requestId input",
  184. );
  185. }
  186. });
  187. /**
  188. * 规格 0.15:回执送不回来时,重试身份要随超时/取消的错误一起送到模型手里。
  189. * 说明里的身份必须与 handler 实际注入的完全一致,否则模型照做也对不上原请求。
  190. */
  191. it("describes the injected request identity on every write tool, and only there", () => {
  192. for (const kind of ["cli", "app"] as const)
  193. for (const tool of sessionControlToolsByKind[kind]) {
  194. const retryable = "retryOf" in (tool.inputSchema.properties ?? {});
  195. expect({
  196. tool: `${kind}:${tool.metadata.name}`,
  197. declares: tool.describeUnsettledCall !== undefined,
  198. }).toEqual({ tool: `${kind}:${tool.metadata.name}`, declares: retryable });
  199. if (!retryable) continue;
  200. // 首次调用:身份是本次 toolCallId;重试:身份是模型回放的 retryOf。
  201. expect(tool.describeUnsettledCall!({}, "toolu_first")).toContain("requestId=toolu_first");
  202. expect(tool.describeUnsettledCall!({ retryOf: "toolu_first" }, "toolu_second")).toContain(
  203. "requestId=toolu_first",
  204. );
  205. expect(tool.describeUnsettledCall!({}, "toolu_first")).toContain("`retryOf`");
  206. }
  207. });
  208. // 规格 0.12:名字必须是无下划线的 PascalCase。snake_case 会命中 App 端
  209. // resolveLegacyKindFamily 的 `^read(?:_|$)` / `^list(?:_|$)` / `(?:^|_)create(?:_|$)` 前缀启发式,
  210. // 把 ReadSession 渲染成读文件卡、ListSessions 渲染成搜索卡、CreateSession 渲染成写文件卡。
  211. it("names every tool in PascalCase so no underscore prefix heuristic can claim it", () => {
  212. for (const tool of sessionControlTools)
  213. expect(tool.metadata.name).toMatch(/^[A-Z][A-Za-z0-9]*$/);
  214. });
  215. // 规格 0.11:工具层只暴露 sessionId。模型曾把 session 也当必填、用 "dummy" 补齐嵌套引用,
  216. // 整轮调用因此全部失败;完整引用退回端口与返回值,模型不再看见。
  217. it("exposes only sessionId on every target tool", () => {
  218. for (const kind of ["cli", "app"] as const)
  219. for (const tool of sessionControlToolsByKind[kind]) {
  220. const properties = Object.keys(tool.inputSchema.properties ?? {});
  221. if (!properties.includes("sessionId")) continue;
  222. expect(properties, `${kind}:${tool.metadata.name}`).not.toContain("session");
  223. expect(tool.inputSchema.required ?? [], tool.metadata.name).toContain("sessionId");
  224. }
  225. const wait = entry("WaitSessions", "app").inputSchema.properties?.operations as {
  226. items: { properties: Record<string, unknown>; required: string[] };
  227. };
  228. expect(Object.keys(wait.items.properties)).toEqual(["sessionId", "commandId"]);
  229. expect([...wait.items.required].sort()).toEqual(["commandId", "sessionId"]);
  230. });
  231. // 会话输入来源(docs/design/v2/conversation-input-source.md §3):来源只由可信 Host 写入。
  232. // 模型能调用的会话控制工具一律不暴露 source,多带即被 strict 入参拒绝,facade 不会被调用。
  233. it("never lets the model set a conversation input source", async () => {
  234. const forged = { kind: "extension", pluginId: "forged@zcode-plugins-example" };
  235. for (const kind of ["cli", "app"] as const)
  236. for (const tool of sessionControlToolsByKind[kind]) {
  237. expect(
  238. tool.inputSchema.properties ?? {},
  239. `${kind}:${tool.metadata.name}`,
  240. ).not.toHaveProperty("source");
  241. expect(tool.inputSchema.additionalProperties, `${kind}:${tool.metadata.name}`).toBe(false);
  242. }
  243. const sendToSession = vi.fn();
  244. const createSession = vi.fn();
  245. const ctx = context({ sendToSession, createSession });
  246. await expect(
  247. entry("SendToSession").handler(
  248. { sessionId: target.sessionId, prompt: "hello", source: forged },
  249. ctx,
  250. ),
  251. ).rejects.toThrow();
  252. await expect(
  253. entry("CreateSession").handler({ prompt: "hello", source: forged }, ctx),
  254. ).rejects.toThrow();
  255. expect(sendToSession).not.toHaveBeenCalled();
  256. expect(createSession).not.toHaveBeenCalled();
  257. });
  258. it("hides control bindings from every child kind and from a different root", () => {
  259. const binding = context({}).sessionControl;
  260. for (const taskType of [
  261. "subagent_child",
  262. "workflow_child",
  263. "nested_workflow_child",
  264. "selection_side_chat",
  265. ] as const) {
  266. expect(sessionControlForRuntime(binding, taskType, "caller")).toBeUndefined();
  267. }
  268. expect(sessionControlForRuntime(binding, "interactive", "other")).toBeUndefined();
  269. expect(sessionControlForRuntime(binding, "interactive", "caller")).toBe(binding);
  270. });
  271. it("declares deferred discoverable bounded tools and conservative mutation permissions", () => {
  272. for (const tool of sessionControlTools) {
  273. expect(tool.metadata.shouldDefer).toBe(true);
  274. expect(tool.metadata.searchHint).toBeTruthy();
  275. expect(tool.resultBudget.maxModelBytes).toBeLessThanOrEqual(32_768);
  276. expect(tool.runtimeInputSchema).toBeDefined();
  277. expect(tool.runtimeOutputSchema).toBeDefined();
  278. expect(tool.metadata.sideEffectScope).toBe(tool.metadata.readOnly ? "none" : "system");
  279. expect(tool.permission.needsApproval).toBe(!tool.metadata.readOnly);
  280. expect(tool.permission.denyPriority).toBe("beforeAsk");
  281. expect(tool.cancellation.supported).toBe(true);
  282. }
  283. });
  284. it("binds identity and cancellation to execution context, preserving request identity", async () => {
  285. const readSession = vi.fn(async () => ({ view: "messages", session: target, messages: [] }));
  286. const ctx = context({ readSession });
  287. await entry("ReadSession").handler({ sessionId: "sess_target", view: "messages" }, ctx);
  288. expect(readSession).toHaveBeenCalledWith(
  289. expect.objectContaining({ callerId: "trusted-caller", rootSession, signal: ctx.abortSignal }),
  290. { sessionId: "sess_target", view: "messages" },
  291. );
  292. });
  293. it("rejects model supplied identities and any full reference before calling the port", async () => {
  294. const readSession = vi.fn();
  295. const tool = entry("ReadSession");
  296. await expect(
  297. tool.handler(
  298. { sessionId: "sess_target", view: "summary", callerId: "forged" },
  299. context({ readSession }),
  300. ),
  301. ).rejects.toThrow();
  302. // 完整引用已不在工具面上:无论本 surface 还是跨 surface 的引用都被 strictObject 拒绝。
  303. for (const session of [target, { ...target, kind: "app" }])
  304. await expect(
  305. tool.handler({ session, view: "summary" }, context({ readSession })),
  306. ).rejects.toThrow();
  307. expect(readSession).not.toHaveBeenCalled();
  308. });
  309. it("rejects a child and a mismatched root even if a binding was accidentally supplied", async () => {
  310. const readSession = vi.fn();
  311. const input = { sessionId: "sess_target", view: "summary" };
  312. await expect(
  313. entry("ReadSession").handler(input, {
  314. ...context({ readSession }),
  315. runtimeScope: "subagent",
  316. }),
  317. ).rejects.toThrow();
  318. await expect(
  319. entry("ReadSession").handler(input, {
  320. ...context({ readSession }),
  321. sessionId: "other" as never,
  322. }),
  323. ).rejects.toThrow();
  324. await expect(
  325. entry("ReadSession", "app").handler(
  326. { sessionId: "sess_target", view: "summary" },
  327. context({ readSession }),
  328. ),
  329. ).rejects.toThrow();
  330. expect(readSession).not.toHaveBeenCalled();
  331. });
  332. it("keeps App discovery schemas and descriptions separate from CLI lists", async () => {
  333. const searchScope = {
  334. scopes: [{ kind: "app" as const, scope: "host" as const, sourceServerId: "source" }],
  335. unavailableSources: [{ sourceServerId: "remote", reason: "disconnected" }],
  336. };
  337. const listSessions = vi.fn(async () => ({ sessions: [], searchScope }));
  338. const listProjects = vi.fn(async () => ({ projects: [], searchScope }));
  339. const trusted = {
  340. callerId: "trusted-caller",
  341. rootSession: { ...rootSession, kind: "app" as const },
  342. allowedScopes: [],
  343. discoveryScopes: searchScope.scopes,
  344. };
  345. const ctx: ToolExecutionContext = {
  346. ...context({}),
  347. sessionControl: {
  348. kind: "app",
  349. context: () => trusted,
  350. control: { listSessions, listProjects } as unknown as AppSessionControl,
  351. },
  352. };
  353. await expect(entry("ListSessions", "app").handler({ query: "小说" }, ctx)).resolves.toEqual({
  354. sessions: [],
  355. searchScope,
  356. });
  357. expect(listSessions).toHaveBeenCalledWith(expect.objectContaining(trusted), {
  358. query: "小说",
  359. archived: "exclude",
  360. });
  361. await expect(entry("ListProjects", "app").handler({}, ctx)).resolves.toEqual({
  362. projects: [],
  363. searchScope,
  364. });
  365. for (const name of ["ListSessions", "ListProjects"]) {
  366. expect(entry(name, "app").outputSchema.required).toContain("searchScope");
  367. expect(entry(name, "app").metadata.description).toContain("searchScope");
  368. expect(entry(name, "app").metadata.description).toContain("unavailableSources");
  369. expect(entry(name, "app").metadata.description).toContain("empty");
  370. expect(entry(name, "app").metadata.description).toContain(
  371. "Empty scopes means no range was successfully searched",
  372. );
  373. }
  374. expect(entry("ListSessions", "app").metadata.description).toContain("across projects");
  375. expect(entry("ListSessions", "app").metadata.description).toContain("title substring");
  376. expect(entry("ListSessions", "app").metadata.description).toContain("not full-text");
  377. expect(entry("ListSessions", "app").metadata.description).toContain(
  378. "Search unarchived sessions first",
  379. );
  380. expect(entry("ListSessions", "app").metadata.description).toContain('archived:"only"');
  381. await entry("ListSessions", "app").handler({ query: "小说", archived: "only" }, ctx);
  382. expect(listSessions).toHaveBeenLastCalledWith(expect.objectContaining(trusted), {
  383. query: "小说",
  384. archived: "only",
  385. });
  386. listSessions.mockResolvedValue({ sessions: [] } as never);
  387. listProjects.mockResolvedValue({ projects: [] } as never);
  388. await expect(entry("ListSessions", "app").handler({}, ctx)).rejects.toThrow();
  389. await expect(entry("ListProjects", "app").handler({}, ctx)).rejects.toThrow();
  390. expect(entry("ListSessions").outputSchema.required).not.toContain("searchScope");
  391. await expect(
  392. entry("ListSessions").handler({}, context({ listSessions: async () => ({ sessions: [] }) })),
  393. ).resolves.toEqual({ sessions: [] });
  394. });
  395. it("describes stable forks, input-bound waits and permission isolation", () => {
  396. expect(entry("ForkSession").metadata.description).toContain("stable");
  397. expect(entry("WaitSessions").metadata.description).toContain("does not stop");
  398. expect(entry("SendToSession", "app").metadata.modelInstructions?.join(" ")).toContain(
  399. "permissions",
  400. );
  401. const registry = createToolRegistry();
  402. registerBuiltInTools(registry, { sessionControlKind: "app" });
  403. expect(
  404. registry.toContracts().find((tool) => tool.name === "CreateSession")?.description,
  405. ).toContain("permissions");
  406. });
  407. });