runtime-reasoning-provider-replay.test.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  1. import { mkdtemp, rm } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { DatabaseSync } from "node:sqlite";
  5. import { describe, expect, it, vi } from "vitest";
  6. import {
  7. InMemorySessionEventStore,
  8. SESSION_ENTRY_MODEL_SELECTION,
  9. createMessageId,
  10. createModelId,
  11. createModelProviderId,
  12. createPartId,
  13. createProjectId,
  14. createSessionId,
  15. parseModelSelectionValue,
  16. type Model,
  17. type ModelRequest,
  18. type SessionId,
  19. } from "@zcode/contracts";
  20. import {
  21. createRegistryModelConfig,
  22. createRegistryProviderConfig,
  23. parseModelConfig,
  24. parseProviderConfig,
  25. } from "@zcode/provider";
  26. import { createSqliteSessionStore } from "../src/storage/session-store/sqlite-session-store.js";
  27. import { AiSdkModelAdapter } from "../src/model/runner.js";
  28. import { orderGeneratedContent } from "../src/model/runner-normalization.js";
  29. import { createTestModelProperties } from "./test-model-format.js";
  30. import { AgentRuntime } from "../../core/src/runtime.js";
  31. const MODEL_ID = createModelId("GLM-5.3");
  32. const USER_ID = createMessageId("old-user");
  33. const ASSISTANT_ID = createMessageId("old-assistant");
  34. const SIGNATURE = "fixture-signature\nopaque ";
  35. const REDACTED_DATA = "fixture-redacted-opaque";
  36. const HISTORICAL_CONTENT = [
  37. { type: "thinking", thinking: "Historical thinking", signature: SIGNATURE },
  38. { type: "redacted_thinking", data: REDACTED_DATA },
  39. { type: "text", text: "Inspecting report" },
  40. { type: "tool_use", id: "old-read", name: "Read", input: { file_path: "report.txt" } },
  41. ];
  42. const cases = ["zai", "bigmodel"].flatMap((family) => {
  43. const legacy = `builtin:${family}-coding-plan`;
  44. const individual = `account:${family}-individual-coding-plan`;
  45. const team = `account:${family}-team-coding-plan`;
  46. return [
  47. [legacy, individual],
  48. [legacy, team],
  49. [individual, team],
  50. [team, individual],
  51. ] as const;
  52. });
  53. describe.each(["off", "on"] as const)(
  54. "Runtime reasoning replay (streaming=%s)",
  55. (modelStreaming) => {
  56. it.each(cases)(
  57. "restores %s and replays into %s without changing old bytes",
  58. async (source, target) => {
  59. const root = await mkdtemp(join(tmpdir(), "zcode-reasoning-replay-"));
  60. const sessionID = createSessionId("reasoning-replay");
  61. let store = await createSqliteSessionStore({ dbPath: join(root, "session.sqlite") });
  62. const db = new DatabaseSync(join(root, "session.sqlite"));
  63. let runtime: AgentRuntime | undefined;
  64. try {
  65. // 合并修复:空库建表后移除尚未播种的迁移记录,模拟升级前数据;只操作临时夹具。
  66. db.prepare("DELETE FROM schema_migration WHERE id = ?").run(
  67. "0020_provider_model_selection",
  68. );
  69. await seedHistory({ db, store, root, sessionID, providerId: source });
  70. const snapshot = () => ({
  71. messages: db
  72. .prepare("select data from message where id in (?, ?) order by id")
  73. .all(USER_ID, ASSISTANT_ID),
  74. parts: db
  75. .prepare("select data from part where message_id in (?, ?) order by id")
  76. .all(USER_ID, ASSISTANT_ID),
  77. });
  78. const before = snapshot();
  79. // Todo109 已将迁移收进数据库启动;不能恢复已删除的逐 Session 迁移接口。
  80. store.close();
  81. store = await createSqliteSessionStore({ dbPath: join(root, "session.sqlite") });
  82. const migrated = snapshot();
  83. expect(migrated.messages).toHaveLength(before.messages.length);
  84. for (const [index, row] of before.messages.entries()) {
  85. expect(JSON.parse(String(migrated.messages[index]!.data))).toMatchObject(
  86. JSON.parse(String(row.data)),
  87. );
  88. }
  89. expect(migrated.parts).toEqual(before.parts);
  90. const entries = await store.sessionEntries({
  91. sessionID,
  92. type: SESSION_ENTRY_MODEL_SELECTION,
  93. });
  94. const selection = parseModelSelectionValue(entries.at(-1)?.data);
  95. if (!selection) throw new Error("Missing restored model selection");
  96. expect(selection.providerId).toBe(
  97. source.startsWith("builtin:")
  98. ? source
  99. .replace("builtin:", "account:")
  100. .replace("-coding-plan", "-individual-coding-plan")
  101. : source,
  102. );
  103. const decoded = (await store.messages({ sessionID })).find(
  104. (message) => message.info.id === ASSISTANT_ID,
  105. );
  106. expect(decoded?.info).toMatchObject({ providerId: source, modelId: MODEL_ID });
  107. const bodies: Array<{ messages: Array<{ role: string; content: unknown[] }> }> = [];
  108. vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => {
  109. const request = new Request(input, init);
  110. expect(request.url).toBe("https://reasoning.invalid/v1/messages");
  111. bodies.push(await request.json());
  112. return modelResponse(modelStreaming === "on");
  113. });
  114. const provider = createRegistryProviderConfig(
  115. parseProviderConfig({
  116. group: "standard-personal",
  117. access: { type: "api-key", apiKey: "fixture-key" },
  118. api: { type: "anthropic-messages", baseUrl: "https://reasoning.invalid/v1" },
  119. }),
  120. );
  121. const model = createRegistryModelConfig(
  122. parseModelConfig({
  123. enabled: true,
  124. properties: createTestModelProperties(),
  125. optionSpecs: {
  126. reasoningLevel: { values: ["disabled"], map: "{}" },
  127. maxOutputTokens: { max: 32_000, map: '{"max_tokens": maxOutputTokens}' },
  128. },
  129. }),
  130. );
  131. if (!provider.ok || !model.ok) throw new Error("Invalid model fixture config");
  132. const adapter = new AiSdkModelAdapter({
  133. env: {},
  134. retry: { maxAttempts: 1 },
  135. });
  136. const requests: ModelRequest[] = [];
  137. runtime = new AgentRuntime(
  138. sessionID,
  139. {
  140. mode: "build",
  141. modelStreaming,
  142. workingDirectory: root,
  143. modelSelection: selection,
  144. memory: { enabled: false },
  145. compact: { enabled: false },
  146. },
  147. {
  148. sessionStore: store,
  149. eventStore: new InMemorySessionEventStore({ retention: "unbounded" }),
  150. modelFactory: ({ selection }) =>
  151. observeModel(
  152. adapter.createModel({
  153. providerId: selection.providerId,
  154. modelId: selection.modelId,
  155. providerConfig: provider.config,
  156. modelConfig: model.config,
  157. options: { maxOutputTokens: 32_000, ...selection.options },
  158. }),
  159. requests,
  160. ),
  161. },
  162. );
  163. await runtime.resumeFromStore();
  164. runtime.setSessionModelSelection({
  165. ...selection,
  166. providerId: createModelProviderId(target),
  167. });
  168. await runtime.executeTurn("Continue after restart");
  169. expect(bodies).toHaveLength(1);
  170. const assistant = bodies[0]!.messages.find((message) => message.role === "assistant");
  171. expect(assistant?.content).toEqual(HISTORICAL_CONTENT);
  172. expect(bodies[0]!.messages).toContainEqual(
  173. expect.objectContaining({
  174. role: "user",
  175. content: expect.arrayContaining([
  176. expect.objectContaining({
  177. type: "tool_result",
  178. tool_use_id: "old-read",
  179. content: "Report content",
  180. }),
  181. ]),
  182. }),
  183. );
  184. await runtime.executeTurn("Continue the same task again");
  185. expect(bodies).toHaveLength(2);
  186. expect(
  187. bodies[1]!.messages.find((message) => message.role === "assistant")?.content,
  188. ).toEqual(assistant?.content);
  189. const canonical = requests[0]!.messages.find((message) => message.role === "assistant");
  190. expect(canonical).toMatchObject({ providerId: source, modelId: MODEL_ID });
  191. expect(canonical?.content).toEqual(
  192. expect.arrayContaining([
  193. {
  194. type: "reasoning",
  195. text: "Historical thinking",
  196. providerOptions: { anthropic: { signature: SIGNATURE } },
  197. },
  198. {
  199. type: "reasoning",
  200. text: "",
  201. providerOptions: { anthropic: { redactedData: REDACTED_DATA } },
  202. },
  203. ]),
  204. );
  205. expect(snapshot()).toEqual(migrated);
  206. } finally {
  207. runtime?.beginShutdown();
  208. vi.unstubAllGlobals();
  209. db.close();
  210. store.close();
  211. await rm(root, { recursive: true, force: true });
  212. }
  213. },
  214. );
  215. },
  216. );
  217. describe.each(["off", "on"] as const)(
  218. "Runtime signature repair marker (streaming=%s)",
  219. (modelStreaming) => {
  220. it("keeps reasoning removed by a repair out of later requests and after cold resume", async () => {
  221. const root = await mkdtemp(join(tmpdir(), "zcode-reasoning-repair-"));
  222. const sessionID = createSessionId("reasoning-repair");
  223. const providerId = "account:zai-individual-coding-plan";
  224. const store = await createSqliteSessionStore({ dbPath: join(root, "session.sqlite") });
  225. const db = new DatabaseSync(join(root, "session.sqlite"));
  226. const runtimes: AgentRuntime[] = [];
  227. try {
  228. await seedHistory({ db, store, root, sessionID, providerId });
  229. const seededRows = () => ({
  230. messages: db
  231. .prepare("select data from message where id in (?, ?) order by id")
  232. .all(USER_ID, ASSISTANT_ID),
  233. parts: db
  234. .prepare("select data from part where message_id in (?, ?) order by id")
  235. .all(USER_ID, ASSISTANT_ID),
  236. });
  237. const seeded = seededRows();
  238. const bodies: string[] = [];
  239. vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => {
  240. const body = await new Request(input, init).text();
  241. bodies.push(body);
  242. // 模拟服务端的前缀校验:恢复后的历史签名块一律被拒,去掉之后才放行。
  243. return body.includes("fixture-signature") || body.includes(REDACTED_DATA)
  244. ? signatureRejection()
  245. : modelResponse(modelStreaming === "on");
  246. });
  247. const selection = parseModelSelectionValue(
  248. (await store.sessionEntries({ sessionID, type: SESSION_ENTRY_MODEL_SELECTION })).at(-1)
  249. ?.data,
  250. );
  251. if (!selection) throw new Error("Missing seeded model selection");
  252. const startRuntime = async () => {
  253. const runtime = createReplayRuntime({
  254. root,
  255. sessionID,
  256. store,
  257. modelStreaming,
  258. selection,
  259. });
  260. runtimes.push(runtime);
  261. await runtime.resumeFromStore();
  262. return runtime;
  263. };
  264. const hasSignedReasoning = (body: string) =>
  265. body.includes("fixture-signature") || body.includes(REDACTED_DATA);
  266. const firstAssistantContent = (body: string) =>
  267. (
  268. JSON.parse(body) as { messages: Array<{ role: string; content: unknown }> }
  269. ).messages.find((message) => message.role === "assistant")?.content;
  270. const live = await startRuntime();
  271. await live.executeTurn("Continue after restart");
  272. expect(bodies.map(hasSignedReasoning)).toEqual([true, false]);
  273. await live.executeTurn("Continue the same task again");
  274. expect(bodies).toHaveLength(3);
  275. expect(hasSignedReasoning(bodies[2]!)).toBe(false);
  276. expect(firstAssistantContent(bodies[2]!)).toEqual(firstAssistantContent(bodies[1]!));
  277. const assistants = (await store.messages({ sessionID })).filter(
  278. (message) => message.info.role === "assistant" && message.info.id !== ASSISTANT_ID,
  279. );
  280. expect(assistants.map((message) => message.info.metadata?.signedReasoningReset)).toEqual([
  281. true,
  282. undefined,
  283. ]);
  284. expect(seededRows()).toEqual(seeded);
  285. live.beginShutdown();
  286. const resumed = await startRuntime();
  287. await resumed.executeTurn("Continue after another restart");
  288. expect(bodies).toHaveLength(4);
  289. expect(hasSignedReasoning(bodies[3]!)).toBe(false);
  290. expect(firstAssistantContent(bodies[3]!)).toEqual(firstAssistantContent(bodies[1]!));
  291. } finally {
  292. for (const runtime of runtimes) runtime.beginShutdown();
  293. vi.unstubAllGlobals();
  294. db.close();
  295. store.close();
  296. await rm(root, { recursive: true, force: true });
  297. }
  298. });
  299. },
  300. );
  301. function createReplayRuntime(input: {
  302. root: string;
  303. sessionID: SessionId;
  304. store: Awaited<ReturnType<typeof createSqliteSessionStore>>;
  305. modelStreaming: "off" | "on";
  306. selection: NonNullable<ReturnType<typeof parseModelSelectionValue>>;
  307. }): AgentRuntime {
  308. const provider = createRegistryProviderConfig(
  309. parseProviderConfig({
  310. group: "standard-personal",
  311. access: { type: "api-key", apiKey: "fixture-key" },
  312. api: { type: "anthropic-messages", baseUrl: "https://reasoning.invalid/v1" },
  313. }),
  314. );
  315. const model = createRegistryModelConfig(
  316. parseModelConfig({
  317. enabled: true,
  318. properties: createTestModelProperties(),
  319. optionSpecs: {
  320. reasoningLevel: { values: ["disabled"], map: "{}" },
  321. maxOutputTokens: { max: 32_000, map: '{"max_tokens": maxOutputTokens}' },
  322. },
  323. }),
  324. );
  325. if (!provider.ok || !model.ok) throw new Error("Invalid model fixture config");
  326. const adapter = new AiSdkModelAdapter({ env: {}, retry: { maxAttempts: 1 } });
  327. return new AgentRuntime(
  328. input.sessionID,
  329. {
  330. mode: "build",
  331. modelStreaming: input.modelStreaming,
  332. workingDirectory: input.root,
  333. modelSelection: input.selection,
  334. memory: { enabled: false },
  335. compact: { enabled: false },
  336. },
  337. {
  338. sessionStore: input.store,
  339. eventStore: new InMemorySessionEventStore({ retention: "unbounded" }),
  340. modelFactory: ({ selection }) =>
  341. adapter.createModel({
  342. providerId: selection.providerId,
  343. modelId: selection.modelId,
  344. providerConfig: provider.config,
  345. modelConfig: model.config,
  346. options: { maxOutputTokens: 32_000, ...selection.options },
  347. }),
  348. },
  349. );
  350. }
  351. function signatureRejection(): Response {
  352. return new Response(
  353. JSON.stringify({
  354. type: "error",
  355. error: {
  356. type: "invalid_request_error",
  357. message:
  358. "messages.1.content.0: Invalid `signature` in `thinking` block. The block is bound to a different conversation.",
  359. },
  360. }),
  361. { status: 400, headers: { "content-type": "application/json" } },
  362. );
  363. }
  364. function observeModel(model: Model, requests: ModelRequest[]): Model {
  365. return {
  366. ...model,
  367. bind: (options) => observeModel(model.bind(options), requests),
  368. generateText(request) {
  369. requests.push(request);
  370. return model.generateText(request);
  371. },
  372. streamText(request) {
  373. requests.push(request);
  374. return model.streamText(request);
  375. },
  376. };
  377. }
  378. async function seedHistory(input: {
  379. db: DatabaseSync;
  380. store: Awaited<ReturnType<typeof createSqliteSessionStore>>;
  381. root: string;
  382. sessionID: SessionId;
  383. providerId: string;
  384. }) {
  385. const { db, store, root, sessionID, providerId } = input;
  386. const legacy = providerId.startsWith("builtin:");
  387. await store.createSession({
  388. id: sessionID,
  389. projectID: createProjectId("reasoning-replay"),
  390. directory: root,
  391. slug: "replay",
  392. title: "Replay",
  393. version: "old",
  394. });
  395. const modelSelection = { providerId, modelId: MODEL_ID, options: { reasoningLevel: "disabled" } };
  396. // 已发布旧格式直接写入 SQLite,避免用新版 writer 生成伪旧数据。
  397. const insert = db.prepare(
  398. "insert into message(id,session_id,sequence,time_created,time_updated,data) values(?,?,?,?,?,?)",
  399. );
  400. insert.run(
  401. USER_ID,
  402. sessionID,
  403. 1,
  404. 1,
  405. 1,
  406. JSON.stringify({
  407. role: "user",
  408. agent: "zcode-agent",
  409. time: { created: 1 },
  410. ...(legacy
  411. ? { model: { providerID: providerId, modelID: MODEL_ID, variant: "disabled" } }
  412. : { modelSelection }),
  413. }),
  414. );
  415. insert.run(
  416. ASSISTANT_ID,
  417. sessionID,
  418. 2,
  419. 2,
  420. 3,
  421. JSON.stringify({
  422. role: "assistant",
  423. time: { created: 2, completed: 3 },
  424. parentID: USER_ID,
  425. ...(legacy
  426. ? { providerID: providerId, modelID: MODEL_ID, variant: "disabled" }
  427. : { providerId, modelId: MODEL_ID, reasoningLevel: "disabled" }),
  428. mode: "build",
  429. agent: "zcode-agent",
  430. path: { cwd: root, root },
  431. cost: 0,
  432. tokens: { input: 20, output: 5, reasoning: 2, cache: { read: 0, write: 0 } },
  433. finish: "tool-calls",
  434. }),
  435. );
  436. db.prepare(
  437. "insert into session_entry(id,session_id,type,time_created,time_updated,data) values(?,?,?,?,?,?)",
  438. ).run(
  439. `${sessionID}:runtime-model-selection`,
  440. sessionID,
  441. SESSION_ENTRY_MODEL_SELECTION,
  442. 1,
  443. 1,
  444. JSON.stringify(
  445. legacy ? { providerId, modelId: MODEL_ID, thoughtLevel: "disabled" } : { modelSelection },
  446. ),
  447. );
  448. for (const [id, text, metadata] of [
  449. ["signed", "Historical thinking", { anthropic: { signature: SIGNATURE } }],
  450. ["redacted", "", { anthropic: { redactedData: REDACTED_DATA } }],
  451. ] as const) {
  452. await store.savePart({
  453. id: createPartId(id),
  454. sessionID,
  455. messageID: ASSISTANT_ID,
  456. type: "reasoning",
  457. text,
  458. metadata,
  459. time: { start: 2, end: 3 },
  460. });
  461. }
  462. for (const [messageID, text] of [
  463. [USER_ID, "Inspect report"],
  464. [ASSISTANT_ID, "Inspecting report"],
  465. ] as const) {
  466. await store.savePart({
  467. id: createPartId(`${messageID}-text`),
  468. sessionID,
  469. messageID,
  470. type: "text",
  471. text,
  472. time: { start: 1, end: 3 },
  473. });
  474. }
  475. await store.savePart({
  476. id: createPartId("read"),
  477. sessionID,
  478. messageID: ASSISTANT_ID,
  479. type: "tool",
  480. tool: "Read",
  481. callID: "old-read",
  482. state: {
  483. status: "completed",
  484. input: { file_path: "report.txt" },
  485. output: "Report content",
  486. title: "Report",
  487. metadata: {},
  488. time: { start: 2, end: 3 },
  489. },
  490. });
  491. }
  492. function modelResponse(streaming: boolean): Response {
  493. const message = {
  494. id: "msg_replay",
  495. model: MODEL_ID,
  496. role: "assistant",
  497. type: "message",
  498. stop_reason: "end_turn",
  499. stop_sequence: null,
  500. usage: { input_tokens: 20, output_tokens: 1 },
  501. content: [{ type: "text", text: "done" }],
  502. };
  503. if (!streaming)
  504. return new Response(JSON.stringify(message), {
  505. headers: { "content-type": "application/json" },
  506. });
  507. const events = [
  508. {
  509. type: "message_start",
  510. message: {
  511. ...message,
  512. content: [],
  513. stop_reason: null,
  514. usage: { input_tokens: 20, output_tokens: 0 },
  515. },
  516. },
  517. { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
  518. { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "done" } },
  519. { type: "content_block_stop", index: 0 },
  520. {
  521. type: "message_delta",
  522. delta: { stop_reason: "end_turn", stop_sequence: null },
  523. usage: { output_tokens: 1 },
  524. },
  525. { type: "message_stop" },
  526. ];
  527. return new Response(
  528. events.map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""),
  529. { headers: { "content-type": "text/event-stream" } },
  530. );
  531. }
  532. // docs/design/v2/model/assistant-block-order.md:交错响应按流顺序保存,live 与冷恢复发出相同字节。
  533. const INTERLEAVED_CONTENT = [
  534. { type: "thinking", thinking: "First thought", signature: "sig-first" },
  535. { type: "text", text: "Let me check." },
  536. { type: "thinking", thinking: "Second thought", signature: "sig-second" },
  537. { type: "text", text: "Reading now." },
  538. { type: "tool_use", id: "toolu_read", name: "Read", input: { file_path: "report.txt" } },
  539. ];
  540. describe.each(["off", "on"] as const)(
  541. "Runtime assistant block order replay (streaming=%s)",
  542. (modelStreaming) => {
  543. it("sends the same interleaved assistant bytes live and after cold resume", async () => {
  544. const root = await mkdtemp(join(tmpdir(), "zcode-block-order-"));
  545. const dbPath = join(root, "session.sqlite");
  546. const sessionID = createSessionId("block-order");
  547. let store = await createSqliteSessionStore({ dbPath });
  548. const runtimes: AgentRuntime[] = [];
  549. const bodies: Array<{ messages: Array<{ role: string; content: unknown }> }> = [];
  550. try {
  551. await store.createSession({
  552. id: sessionID,
  553. projectID: createProjectId("block-order"),
  554. directory: root,
  555. slug: "block-order",
  556. title: "Block order",
  557. version: "test",
  558. });
  559. vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => {
  560. const request = new Request(input, init);
  561. bodies.push(await request.json());
  562. const streaming = modelStreaming === "on";
  563. return bodies.length === 1
  564. ? anthropicResponse(INTERLEAVED_CONTENT, "tool_use", streaming)
  565. : anthropicResponse([{ type: "text", text: "done" }], "end_turn", streaming);
  566. });
  567. const createRuntime = () => {
  568. const runtime = createAnthropicRuntime({ root, sessionID, store, modelStreaming });
  569. runtimes.push(runtime);
  570. return runtime;
  571. };
  572. const live = createRuntime();
  573. await live.executeTurn("Inspect report");
  574. await live.executeTurn("Follow up");
  575. expect(bodies).toHaveLength(3);
  576. const firstAssistant = (body: (typeof bodies)[number]) =>
  577. body.messages.find((message) => message.role === "assistant")?.content;
  578. // 两段文字不合并;tool_use 后面没有其他块,保持原顺序。
  579. expect(stripCacheControl(firstAssistant(bodies[1]!))).toEqual(INTERLEAVED_CONTENT);
  580. expect(stripCacheControl(firstAssistant(bodies[2]!))).toEqual(INTERLEAVED_CONTENT);
  581. live.beginShutdown();
  582. store.close();
  583. store = await createSqliteSessionStore({ dbPath });
  584. const cold = createRuntime();
  585. await cold.resumeFromStore();
  586. await cold.executeTurn("Follow up");
  587. expect(bodies).toHaveLength(4);
  588. // 冷恢复后的请求以 live 最后一次请求为前缀:同一条交错消息发出相同字节,缓存前缀不变。
  589. const liveMessages = bodies[2]!.messages;
  590. expect(stripCacheControl(bodies[3]!.messages.slice(0, liveMessages.length))).toEqual(
  591. stripCacheControl(liveMessages),
  592. );
  593. } finally {
  594. for (const runtime of runtimes) runtime.beginShutdown();
  595. vi.unstubAllGlobals();
  596. store.close();
  597. await rm(root, { recursive: true, force: true });
  598. }
  599. });
  600. },
  601. );
  602. // 回复只有思考块(send now / 停止在思考中打断、思考后流失败,历史形态相同)时,下一次请求不能把
  603. // MCS system 放在这条回复前面再删掉它:请求会变成 system 直接接 user,provider 返回 400。
  604. describe.each(["off", "on"] as const)(
  605. "Runtime reasoning-only reply with mid-conversation system (streaming=%s)",
  606. (modelStreaming) => {
  607. it("never sends a system message directly before a user message, live and after cold resume", async () => {
  608. const root = await mkdtemp(join(tmpdir(), "zcode-reasoning-only-mcs-"));
  609. const dbPath = join(root, "session.sqlite");
  610. const sessionID = createSessionId("reasoning-only-mcs");
  611. let store = await createSqliteSessionStore({ dbPath });
  612. const runtimes: AgentRuntime[] = [];
  613. const bodies: Array<{ messages: Array<{ role: string; content: unknown }> }> = [];
  614. try {
  615. await store.createSession({
  616. id: sessionID,
  617. projectID: createProjectId("reasoning-only-mcs"),
  618. directory: root,
  619. slug: "reasoning-only-mcs",
  620. title: "Reasoning-only reply",
  621. version: "test",
  622. });
  623. vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => {
  624. const request = new Request(input, init);
  625. bodies.push(await request.json());
  626. const streaming = modelStreaming === "on";
  627. return bodies.length === 1
  628. ? anthropicResponse(
  629. [{ type: "thinking", thinking: "Still thinking", signature: "sig-only" }],
  630. "end_turn",
  631. streaming,
  632. )
  633. : anthropicResponse([{ type: "text", text: "done" }], "end_turn", streaming);
  634. });
  635. const createRuntime = () => {
  636. const runtime = createAnthropicRuntime({ root, sessionID, store, modelStreaming });
  637. runtimes.push(runtime);
  638. return runtime;
  639. };
  640. const roles = (index: number) => bodies[index]!.messages.map((message) => message.role);
  641. const expectValidFollowUp = (index: number) => {
  642. expect(roles(index)).toContain("system");
  643. expect(
  644. roles(index).some((role, at, all) => role === "system" && all[at + 1] === "user"),
  645. ).toBe(false);
  646. expect(JSON.stringify(bodies[index]!.messages)).not.toContain("Still thinking");
  647. };
  648. const live = createRuntime();
  649. await live.executeTurn("Inspect report");
  650. // 前提:第一轮的公告按 MCS 投影成 system。
  651. expect(roles(0)).toContain("system");
  652. await live.executeTurn("Follow up");
  653. expect(bodies).toHaveLength(2);
  654. expectValidFollowUp(1);
  655. live.beginShutdown();
  656. store.close();
  657. store = await createSqliteSessionStore({ dbPath });
  658. const cold = createRuntime();
  659. await cold.resumeFromStore();
  660. await cold.executeTurn("Follow up again");
  661. expect(bodies).toHaveLength(3);
  662. expectValidFollowUp(2);
  663. } finally {
  664. for (const runtime of runtimes) runtime.beginShutdown();
  665. vi.unstubAllGlobals();
  666. store.close();
  667. await rm(root, { recursive: true, force: true });
  668. }
  669. });
  670. },
  671. );
  672. // 非流式结果和规范化后的 text / reasoning / toolCalls 对不上时整条不编号,按旧消息处理;
  673. // 只给一部分块编号会让 live 与冷恢复的文字拼法不同(docs/design/v2/model/assistant-block-order.md「写入」)。
  674. describe("non-stream block numbering fallback", () => {
  675. const call = (id: string) => ({ id, name: "Read", input: { file_path: "a.txt" } });
  676. it("numbers no block when the result has no content list", () => {
  677. const reasoning = [{ type: "reasoning" as const, text: "think" }];
  678. const toolCalls = [call("call-1")];
  679. expect(orderGeneratedContent({} as never, { text: "P", reasoning, toolCalls })).toBeUndefined();
  680. expect(reasoning[0]).not.toHaveProperty("blockIndex");
  681. expect(toolCalls[0]).not.toHaveProperty("blockIndex");
  682. });
  683. // provider 没给 id 时规范化补随机 id,content 里的 tool-call 没有对应 id。
  684. it.each([
  685. ["missing", {}],
  686. ["empty", { toolCallId: "" }],
  687. ])("numbers no block when a tool call id is %s in content", (_label, idField) => {
  688. const reasoning = [{ type: "reasoning" as const, text: "think" }];
  689. const toolCalls = [call("generated-id")];
  690. const content = [
  691. { type: "reasoning", text: "think" },
  692. { type: "text", text: "P" },
  693. { type: "tool-call", toolName: "Read", input: { file_path: "a.txt" }, ...idField },
  694. ];
  695. expect(
  696. orderGeneratedContent({ content } as never, { text: "P", reasoning, toolCalls }),
  697. ).toBeUndefined();
  698. expect(reasoning[0]).not.toHaveProperty("blockIndex");
  699. expect(toolCalls[0]).not.toHaveProperty("blockIndex");
  700. });
  701. });
  702. function createAnthropicRuntime(input: {
  703. root: string;
  704. sessionID: SessionId;
  705. store: Awaited<ReturnType<typeof createSqliteSessionStore>>;
  706. modelStreaming: "on" | "off";
  707. }): AgentRuntime {
  708. const provider = createRegistryProviderConfig(
  709. parseProviderConfig({
  710. group: "standard-personal",
  711. access: { type: "api-key", apiKey: "fixture-key" },
  712. api: { type: "anthropic-messages", baseUrl: "https://reasoning.invalid/v1" },
  713. }),
  714. );
  715. const model = createRegistryModelConfig(
  716. parseModelConfig({
  717. enabled: true,
  718. properties: createTestModelProperties(),
  719. optionSpecs: {
  720. reasoningLevel: { values: ["disabled"], map: "{}" },
  721. maxOutputTokens: { max: 32_000, map: '{"max_tokens": maxOutputTokens}' },
  722. },
  723. }),
  724. );
  725. if (!provider.ok || !model.ok) throw new Error("Invalid model fixture config");
  726. const adapter = new AiSdkModelAdapter({ env: {}, retry: { maxAttempts: 1 } });
  727. return new AgentRuntime(
  728. input.sessionID,
  729. {
  730. mode: "build",
  731. modelStreaming: input.modelStreaming,
  732. workingDirectory: input.root,
  733. modelSelection: {
  734. providerId: createModelProviderId("custom:block-order"),
  735. modelId: MODEL_ID,
  736. options: { reasoningLevel: "disabled" },
  737. },
  738. memory: { enabled: false },
  739. compact: { enabled: false },
  740. },
  741. {
  742. sessionStore: input.store,
  743. eventStore: new InMemorySessionEventStore({ retention: "unbounded" }),
  744. modelFactory: ({ selection }) =>
  745. adapter.createModel({
  746. providerId: selection.providerId,
  747. modelId: selection.modelId,
  748. providerConfig: provider.config,
  749. modelConfig: model.config,
  750. options: { maxOutputTokens: 32_000, ...selection.options },
  751. }),
  752. },
  753. );
  754. }
  755. function stripCacheControl(value: unknown): unknown {
  756. return JSON.parse(JSON.stringify(value), (key, nested) =>
  757. key === "cache_control" ? undefined : nested,
  758. );
  759. }
  760. function anthropicResponse(
  761. content: Array<Record<string, unknown>>,
  762. stopReason: string,
  763. streaming: boolean,
  764. ): Response {
  765. const message = {
  766. id: "msg_block_order",
  767. model: MODEL_ID,
  768. role: "assistant",
  769. type: "message",
  770. stop_reason: stopReason,
  771. stop_sequence: null,
  772. usage: { input_tokens: 20, output_tokens: 5 },
  773. content,
  774. };
  775. if (!streaming) {
  776. return new Response(JSON.stringify(message), {
  777. headers: { "content-type": "application/json" },
  778. });
  779. }
  780. const events: Array<Record<string, unknown>> = [
  781. {
  782. type: "message_start",
  783. message: {
  784. ...message,
  785. content: [],
  786. stop_reason: null,
  787. usage: { input_tokens: 20, output_tokens: 0 },
  788. },
  789. },
  790. ];
  791. content.forEach((block, index) => {
  792. if (block.type === "thinking") {
  793. events.push(
  794. {
  795. type: "content_block_start",
  796. index,
  797. content_block: { type: "thinking", thinking: "", signature: "" },
  798. },
  799. {
  800. type: "content_block_delta",
  801. index,
  802. delta: { type: "thinking_delta", thinking: block.thinking },
  803. },
  804. {
  805. type: "content_block_delta",
  806. index,
  807. delta: { type: "signature_delta", signature: block.signature },
  808. },
  809. );
  810. } else if (block.type === "text") {
  811. events.push(
  812. { type: "content_block_start", index, content_block: { type: "text", text: "" } },
  813. { type: "content_block_delta", index, delta: { type: "text_delta", text: block.text } },
  814. );
  815. } else {
  816. events.push(
  817. { type: "content_block_start", index, content_block: { ...block, input: {} } },
  818. {
  819. type: "content_block_delta",
  820. index,
  821. delta: { type: "input_json_delta", partial_json: JSON.stringify(block.input) },
  822. },
  823. );
  824. }
  825. events.push({ type: "content_block_stop", index });
  826. });
  827. events.push(
  828. {
  829. type: "message_delta",
  830. delta: { stop_reason: stopReason, stop_sequence: null },
  831. usage: { output_tokens: 5 },
  832. },
  833. { type: "message_stop" },
  834. );
  835. return new Response(
  836. events.map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""),
  837. { headers: { "content-type": "text/event-stream" } },
  838. );
  839. }