standalone-bootstrap.test.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. import { mkdtemp, readFile, rm } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, describe, expect, it } from "vitest";
  5. import { createSessionId, type PermissionBrokerRequest, type SessionId } from "@zcode/contracts";
  6. import { createSqliteSessionStore } from "@zcode/adapters/storage";
  7. import { createRegistryBackedTestApp } from "../helpers/registry-backed-test-app.js";
  8. import { cleanups, CLI_TOOLS, APP_ONLY_TOOLS } from "./standalone-bootstrap-fixture.js";
  9. afterEach(async () => {
  10. for (const close of cleanups.splice(0).reverse()) await close();
  11. });
  12. describe("standalone session tools bootstrap", () => {
  13. it("only registers CLI tools at explicit standalone startup and reaches the real root manager", async () => {
  14. const cwd = await mkdtemp(join(tmpdir(), "zcode-control-bootstrap-"));
  15. const store = await createSqliteSessionStore({ dbPath: join(cwd, "sessions.sqlite") });
  16. cleanups.push(async () => {
  17. store.close();
  18. await rm(cwd, { recursive: true, force: true });
  19. });
  20. const sessionId = createSessionId("standalone-root");
  21. let calls = 0;
  22. const root = await createRegistryBackedTestApp({
  23. standaloneSessionControl: true,
  24. sessionId,
  25. sessionStore: store,
  26. skipUserConfig: true,
  27. env: { ZCODE_STORAGE_DIR: cwd },
  28. configuredDefaultModelSelection: { providerId: "zai", modelId: "glm-4.6" },
  29. runtimeConfig: { workingDirectory: cwd, mode: "yolo" },
  30. modelExecutor: {
  31. generateText: async () => {
  32. if (calls++ === 0)
  33. return {
  34. text: "",
  35. finishReason: "tool-calls",
  36. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  37. toolCalls: [
  38. {
  39. id: "rename-root",
  40. name: "RenameSession",
  41. input: {
  42. sessionId,
  43. title: "Renamed through owner",
  44. },
  45. },
  46. ],
  47. };
  48. return {
  49. text: "done",
  50. finishReason: "stop",
  51. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  52. };
  53. },
  54. },
  55. });
  56. cleanups.push(async () => {
  57. await root.close?.();
  58. });
  59. const registry = root.runtime.getToolRegistry();
  60. // 工具名统一后没有前缀:独立 CLI 只注册共有 8 个,App 独有的 4 个不出现。
  61. const registered = registry.list();
  62. expect(CLI_TOOLS.filter((name) => registered.includes(name))).toEqual(CLI_TOOLS);
  63. expect(APP_ONLY_TOOLS.some((name) => registered.includes(name))).toBe(false);
  64. await root.submitPrompt("Rename this session");
  65. expect(calls).toBeGreaterThanOrEqual(2);
  66. expect((await store.getSession(sessionId))?.title).toBe("Renamed through owner");
  67. expect(
  68. (await store.messages({ sessionID: sessionId }))
  69. .flatMap((message) => message.parts)
  70. .some((part) => part.type === "tool" && part.tool === "RenameSession"),
  71. ).toBe(true);
  72. await root.close?.();
  73. });
  74. it.each([true, false])(
  75. "does not grant target write access to persisted history (resume=%s)",
  76. async (resume) => {
  77. const cwd = await mkdtemp(join(tmpdir(), "zcode-control-resume-scope-"));
  78. const store = await createSqliteSessionStore({ dbPath: join(cwd, "sessions.sqlite") });
  79. cleanups.push(async () => {
  80. store.close();
  81. await rm(cwd, { recursive: true, force: true });
  82. });
  83. const sessionId = createSessionId("resumed-root");
  84. const original = await createRegistryBackedTestApp({
  85. sessionId,
  86. sessionStore: store,
  87. skipUserConfig: true,
  88. env: { ZCODE_STORAGE_DIR: cwd },
  89. configuredDefaultModelSelection: { providerId: "zai", modelId: "glm-4.6" },
  90. runtimeConfig: { workingDirectory: cwd, mode: "yolo" },
  91. modelExecutor: {
  92. generateText: async () => ({
  93. text: "seeded",
  94. finishReason: "stop",
  95. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  96. }),
  97. },
  98. });
  99. cleanups.push(async () => {
  100. await original.close?.();
  101. });
  102. await original.submitPrompt("Preserve this independent history");
  103. await original.setCustomSessionTitle({ title: "Original history" });
  104. await original.close?.();
  105. let calls = 0;
  106. const resumed = await createRegistryBackedTestApp({
  107. standaloneSessionControl: true,
  108. resume,
  109. sessionId,
  110. sessionStore: store,
  111. skipUserConfig: true,
  112. env: { ZCODE_STORAGE_DIR: cwd },
  113. runtimeConfig: { workingDirectory: cwd, mode: "yolo" },
  114. modelExecutor: {
  115. generateText: async () => {
  116. if (calls++ === 0)
  117. return {
  118. text: "",
  119. finishReason: "tool-calls",
  120. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  121. toolCalls: [
  122. {
  123. id: "rename-unverified",
  124. name: "RenameSession",
  125. input: {
  126. sessionId,
  127. title: "Must not rename",
  128. },
  129. },
  130. ],
  131. };
  132. return {
  133. text: "not renamed",
  134. finishReason: "stop",
  135. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  136. };
  137. },
  138. },
  139. });
  140. cleanups.push(async () => {
  141. await resumed.close?.();
  142. });
  143. await resumed.submitPrompt("Try session-control rename without owner provenance");
  144. expect(calls).toBeGreaterThanOrEqual(2);
  145. const finalTitle = (await store.getSession(sessionId))?.title;
  146. expect(finalTitle).not.toBe("Must not rename");
  147. if (resume) expect(finalTitle).toBe("Original history");
  148. const attempted = (await store.messages({ sessionID: sessionId }))
  149. .flatMap((message) => message.parts)
  150. .find((part) => part.type === "tool" && part.callID === "rename-unverified");
  151. expect(attempted).toMatchObject({
  152. type: "tool",
  153. tool: "RenameSession",
  154. state: { status: "error" },
  155. });
  156. },
  157. );
  158. it("creates a real independent root in build mode from a yolo actor and interrupts it on owner close", async () => {
  159. const cwd = await mkdtemp(join(tmpdir(), "zcode-control-root-life-"));
  160. const store = await createSqliteSessionStore({ dbPath: join(cwd, "sessions.sqlite") });
  161. cleanups.push(async () => {
  162. store.close();
  163. await rm(cwd, { recursive: true, force: true });
  164. });
  165. const sessionId = createSessionId("actor-yolo");
  166. let actorCalls = 0;
  167. let childSessionId: string | undefined;
  168. let childStarted!: () => void;
  169. const started = new Promise<void>((resolve) => {
  170. childStarted = resolve;
  171. });
  172. const root = await createRegistryBackedTestApp({
  173. standaloneSessionControl: true,
  174. sessionId,
  175. sessionStore: store,
  176. skipUserConfig: true,
  177. env: { ZCODE_STORAGE_DIR: cwd },
  178. configuredDefaultModelSelection: { providerId: "zai", modelId: "glm-4.6" },
  179. runtimeConfig: { workingDirectory: cwd, mode: "yolo" },
  180. modelExecutor: {
  181. generateText: async (request) => {
  182. if (
  183. request.messages.some(
  184. (message) => message.role === "user" && message.content === "run background work",
  185. )
  186. ) {
  187. childSessionId = (await store.listSessions()).find(
  188. (session) => session.id !== sessionId,
  189. )?.id;
  190. childStarted();
  191. return new Promise((_resolve, reject) => {
  192. if (request.abortSignal?.aborted) reject(request.abortSignal.reason);
  193. else
  194. request.abortSignal?.addEventListener(
  195. "abort",
  196. () => reject(request.abortSignal?.reason),
  197. { once: true },
  198. );
  199. });
  200. }
  201. if (actorCalls++ === 0)
  202. return {
  203. text: "",
  204. finishReason: "tool-calls",
  205. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  206. toolCalls: [
  207. {
  208. id: "create-root",
  209. name: "CreateSession",
  210. input: { prompt: "run background work" },
  211. },
  212. ],
  213. };
  214. return {
  215. text: "created",
  216. finishReason: "stop",
  217. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  218. };
  219. },
  220. },
  221. });
  222. cleanups.push(async () => {
  223. await root.close?.();
  224. });
  225. await root.submitPrompt("Create another root session");
  226. await started;
  227. const child = await store.getSession(childSessionId as SessionId);
  228. expect(child?.taskType).toBe("interactive");
  229. expect(child?.parentID).toBeUndefined();
  230. await root.close?.();
  231. expect((await store.getSession(childSessionId as SessionId))?.lastOutcome).toBe("interrupted");
  232. const assistantMessages = (
  233. await store.messages({ sessionID: childSessionId as SessionId })
  234. ).filter((message) => message.info.role === "assistant");
  235. expect(assistantMessages.length).toBeGreaterThan(0);
  236. expect(
  237. assistantMessages.every(
  238. (message) => message.info.role === "assistant" && message.info.mode === "build",
  239. ),
  240. ).toBe(true);
  241. });
  242. // 回归(会话工具设计 0.5):后台根原先不接启动方的 broker,需要审批的工具被 Core 的拒绝 broker
  243. // 直接拒绝。现在询问进入同一个 broker,带后台会话自己的 sessionId;发起者的 yolo 不传给后台根。
  244. it.each(["allow", "deny"] as const)(
  245. "routes a background root approval to the launcher broker (%s)",
  246. async (decision) => {
  247. const cwd = await mkdtemp(join(tmpdir(), "zcode-control-root-approval-"));
  248. const store = await createSqliteSessionStore({ dbPath: join(cwd, "sessions.sqlite") });
  249. cleanups.push(async () => {
  250. store.close();
  251. await rm(cwd, { recursive: true, force: true });
  252. });
  253. const actorId = createSessionId("actor-approval");
  254. const target = join(cwd, "background.txt");
  255. const asked: PermissionBrokerRequest[] = [];
  256. const backgroundDone = Promise.withResolvers<string>();
  257. let actorCalls = 0;
  258. let backgroundCalls = 0;
  259. const root = await createRegistryBackedTestApp({
  260. standaloneSessionControl: true,
  261. sessionId: actorId,
  262. sessionStore: store,
  263. skipUserConfig: true,
  264. env: { ZCODE_STORAGE_DIR: cwd },
  265. configuredDefaultModelSelection: { providerId: "zai", modelId: "glm-4.6" },
  266. runtimeConfig: { workingDirectory: cwd, mode: "yolo" },
  267. permissionBroker: {
  268. requestPermission: async (request) => {
  269. asked.push(request);
  270. return { decision, reason: `${decision} by launcher test`, resolvedAt: new Date() };
  271. },
  272. },
  273. modelExecutor: {
  274. generateText: async (request) => {
  275. // 只按用户输入区分会话:发起者的 CreateSession 参数里也带标记,不能按整份请求匹配。
  276. const background = request.messages.some(
  277. (message) =>
  278. message.role === "user" &&
  279. JSON.stringify(message.content).includes("E2E_BACKGROUND_WRITE"),
  280. );
  281. if (background) {
  282. if (backgroundCalls++ === 0)
  283. return {
  284. text: "",
  285. finishReason: "tool-calls",
  286. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  287. toolCalls: [
  288. {
  289. id: "background-write",
  290. name: "Write",
  291. input: { file_path: target, content: "written after approval" },
  292. },
  293. ],
  294. };
  295. const result = request.messages.find(
  296. (message) => message.role === "tool" && message.toolCallId === "background-write",
  297. );
  298. backgroundDone.resolve(JSON.stringify(result?.content ?? ""));
  299. return {
  300. text: "background done",
  301. finishReason: "stop",
  302. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  303. };
  304. }
  305. if (actorCalls++ === 0)
  306. return {
  307. text: "",
  308. finishReason: "tool-calls",
  309. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  310. toolCalls: [
  311. {
  312. id: "create-background",
  313. name: "CreateSession",
  314. input: { prompt: "E2E_BACKGROUND_WRITE" },
  315. },
  316. ],
  317. };
  318. return {
  319. text: "created",
  320. finishReason: "stop",
  321. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  322. };
  323. },
  324. },
  325. });
  326. cleanups.push(async () => {
  327. await root.close?.();
  328. });
  329. // 发起者是 yolo,自己的 CreateSession 不询问;询问只来自后台根。
  330. await root.submitPrompt("Create a background writer");
  331. const toolResult = await backgroundDone.promise;
  332. expect(asked).toHaveLength(1);
  333. expect(asked[0]).toMatchObject({ toolName: "Write", mode: "build" });
  334. expect(asked[0]!.sessionId).not.toBe(actorId);
  335. const background = await store.getSession(asked[0]!.sessionId);
  336. expect(background?.parentID).toBeUndefined();
  337. if (decision === "allow") {
  338. expect(await readFile(target, "utf8")).toBe("written after approval");
  339. } else {
  340. await expect(readFile(target, "utf8")).rejects.toMatchObject({ code: "ENOENT" });
  341. expect(toolResult).toContain("deny by launcher test");
  342. }
  343. },
  344. );
  345. // SCT08:后台根等待审批时,发起者的 wait 只看到 needs_attention,不能代答;用户回答后后台根继续。
  346. it("reports needs_attention to the actor while the user has not answered", async () => {
  347. const cwd = await mkdtemp(join(tmpdir(), "zcode-control-root-attention-"));
  348. const store = await createSqliteSessionStore({ dbPath: join(cwd, "sessions.sqlite") });
  349. cleanups.push(async () => {
  350. store.close();
  351. await rm(cwd, { recursive: true, force: true });
  352. });
  353. const target = join(cwd, "attention.txt");
  354. const asked = Promise.withResolvers<PermissionBrokerRequest>();
  355. const answer = Promise.withResolvers<"allow">();
  356. const backgroundDone = Promise.withResolvers<void>();
  357. const waited: unknown[] = [];
  358. let backgroundCalls = 0;
  359. const toolText = (
  360. request: { messages: { role: string; toolCallId?: string; content: unknown }[] },
  361. id: string,
  362. ) => {
  363. const content = request.messages.find(
  364. (message) => message.role === "tool" && message.toolCallId === id,
  365. )?.content;
  366. const text =
  367. typeof content === "string"
  368. ? content
  369. : ((content as { type: string; text?: string }[] | undefined) ?? [])
  370. .filter((block) => block.type === "text")
  371. .map((block) => block.text)
  372. .join("\n");
  373. const reminder = text.indexOf("\n\n<system-reminder>");
  374. return reminder < 0 ? text : text.slice(0, reminder);
  375. };
  376. const root = await createRegistryBackedTestApp({
  377. standaloneSessionControl: true,
  378. sessionStore: store,
  379. skipUserConfig: true,
  380. env: { ZCODE_STORAGE_DIR: cwd },
  381. configuredDefaultModelSelection: { providerId: "zai", modelId: "glm-4.6" },
  382. runtimeConfig: { workingDirectory: cwd, mode: "yolo" },
  383. permissionBroker: {
  384. requestPermission: async (request) => {
  385. asked.resolve(request);
  386. return {
  387. decision: await answer.promise,
  388. reason: "user answered",
  389. resolvedAt: new Date(),
  390. };
  391. },
  392. },
  393. modelExecutor: {
  394. generateText: async (request) => {
  395. const background = request.messages.some(
  396. (message) =>
  397. message.role === "user" &&
  398. JSON.stringify(message.content).includes("E2E_ATTENTION_WRITE"),
  399. );
  400. if (background) {
  401. if (backgroundCalls++ === 0)
  402. return {
  403. text: "",
  404. finishReason: "tool-calls",
  405. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  406. toolCalls: [
  407. {
  408. id: "attention-write",
  409. name: "Write",
  410. input: { file_path: target, content: "written after the user answered" },
  411. },
  412. ],
  413. };
  414. backgroundDone.resolve();
  415. return {
  416. text: "background done",
  417. finishReason: "stop",
  418. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  419. };
  420. }
  421. if (!request.messages.some((message) => message.toolCallId === "create-attention"))
  422. return {
  423. text: "",
  424. finishReason: "tool-calls",
  425. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  426. toolCalls: [
  427. {
  428. id: "create-attention",
  429. name: "CreateSession",
  430. input: { prompt: "E2E_ATTENTION_WRITE" },
  431. },
  432. ],
  433. };
  434. if (!request.messages.some((message) => message.toolCallId === "wait-attention")) {
  435. // operation 只取自真实 CreateSession 回执;工具面只收 sessionId + commandId(规格 0.11)。
  436. const created = JSON.parse(toolText(request, "create-attention")) as {
  437. operation: { session: { sessionId: string }; commandId: string };
  438. };
  439. return {
  440. text: "",
  441. finishReason: "tool-calls",
  442. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  443. toolCalls: [
  444. {
  445. id: "wait-attention",
  446. name: "WaitSessions",
  447. input: {
  448. operations: [
  449. {
  450. sessionId: created.operation.session.sessionId,
  451. commandId: created.operation.commandId,
  452. },
  453. ],
  454. mode: "any",
  455. timeoutMs: 30_000,
  456. },
  457. },
  458. ],
  459. };
  460. }
  461. waited.push(JSON.parse(toolText(request, "wait-attention")));
  462. return {
  463. text: "observed",
  464. finishReason: "stop",
  465. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  466. };
  467. },
  468. },
  469. });
  470. cleanups.push(async () => {
  471. await root.close?.();
  472. });
  473. await root.submitPrompt("Create a background writer and wait for it");
  474. const request = await asked.promise;
  475. // 发起者的这一轮已经结束,用户仍未回答:wait 只报告 needs_attention,文件尚未写入。
  476. expect(waited).toHaveLength(1);
  477. expect(waited[0]).toMatchObject({
  478. status: "completed",
  479. operations: [{ status: "needs_attention", attention: { kind: "approval" } }],
  480. });
  481. expect(request).toMatchObject({ toolName: "Write", mode: "build" });
  482. await expect(readFile(target, "utf8")).rejects.toMatchObject({ code: "ENOENT" });
  483. answer.resolve("allow");
  484. await backgroundDone.promise;
  485. expect(await readFile(target, "utf8")).toBe("written after the user answered");
  486. });
  487. // 规格 0.5:用户切换主会话或进程退出时 owner 关闭后台根,等待中的询问必须被取消,不能悬挂。
  488. it("cancels a pending background approval when the owner closes", async () => {
  489. const cwd = await mkdtemp(join(tmpdir(), "zcode-control-root-approval-close-"));
  490. const store = await createSqliteSessionStore({ dbPath: join(cwd, "sessions.sqlite") });
  491. cleanups.push(async () => {
  492. store.close();
  493. await rm(cwd, { recursive: true, force: true });
  494. });
  495. const target = join(cwd, "cancelled.txt");
  496. const asked = Promise.withResolvers<PermissionBrokerRequest>();
  497. let actorCalls = 0;
  498. let cancelled = false;
  499. const root = await createRegistryBackedTestApp({
  500. standaloneSessionControl: true,
  501. sessionStore: store,
  502. skipUserConfig: true,
  503. env: { ZCODE_STORAGE_DIR: cwd },
  504. configuredDefaultModelSelection: { providerId: "zai", modelId: "glm-4.6" },
  505. runtimeConfig: { workingDirectory: cwd, mode: "yolo" },
  506. permissionBroker: {
  507. requestPermission: (request, options) =>
  508. new Promise((_resolve, reject) => {
  509. options?.signal?.addEventListener(
  510. "abort",
  511. () => {
  512. cancelled = true;
  513. reject(new Error("Permission request cancelled"));
  514. },
  515. { once: true },
  516. );
  517. asked.resolve(request);
  518. }),
  519. },
  520. modelExecutor: {
  521. generateText: async (request) => {
  522. const background = request.messages.some(
  523. (message) =>
  524. message.role === "user" &&
  525. JSON.stringify(message.content).includes("E2E_CANCEL_WRITE"),
  526. );
  527. if (background)
  528. return {
  529. text: "",
  530. finishReason: "tool-calls",
  531. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  532. toolCalls: [
  533. { id: "cancel-write", name: "Write", input: { file_path: target, content: "no" } },
  534. ],
  535. };
  536. if (actorCalls++ === 0)
  537. return {
  538. text: "",
  539. finishReason: "tool-calls",
  540. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  541. toolCalls: [
  542. {
  543. id: "create-cancel",
  544. name: "CreateSession",
  545. input: { prompt: "E2E_CANCEL_WRITE" },
  546. },
  547. ],
  548. };
  549. return {
  550. text: "created",
  551. finishReason: "stop",
  552. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  553. };
  554. },
  555. },
  556. });
  557. cleanups.push(async () => {
  558. await root.close?.();
  559. });
  560. await root.submitPrompt("Create a background writer");
  561. const request = await asked.promise;
  562. await root.close?.();
  563. expect(cancelled).toBe(true);
  564. expect((await store.getSession(request.sessionId))?.lastOutcome).toBe("interrupted");
  565. await expect(readFile(target, "utf8")).rejects.toMatchObject({ code: "ENOENT" });
  566. });
  567. });