provider-builtin-tool-rounds.test.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  1. // 服务端内置工具(analyze_image)多轮回放:真实 GLM 流(脱敏 fixture)经 compat → AI SDK → Runtime,
  2. // 验证下一次请求、持久化顺序和冷恢复回放。背景见 docs/design/v2/model/anthropic-stream-compat.md。
  3. import { mkdtemp, readFile, rm } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import { describe, expect, it, vi } from "vitest";
  7. import {
  8. CompactTrigger,
  9. InMemorySessionEventStore,
  10. SessionEventType,
  11. createModelId,
  12. createModelProviderId,
  13. createRootTraceContext,
  14. createSessionId,
  15. type SessionId,
  16. } from "@zcode/contracts";
  17. import {
  18. createRegistryModelConfig,
  19. createRegistryProviderConfig,
  20. parseModelConfig,
  21. parseProviderConfig,
  22. } from "@zcode/provider";
  23. import { createSqliteSessionStore } from "../src/storage/session-store/sqlite-session-store.js";
  24. import { AiSdkModelAdapter } from "../src/model/runner.js";
  25. import { createTestModelProperties } from "./test-model-format.js";
  26. import { AgentRuntime } from "../../core/src/runtime.js";
  27. import { OUTPUT_TOKEN_CONTINUE_PROMPT } from "../../core/src/runtime/methods/turn-output-token-continuation.js";
  28. import { PROVIDER_TOOL_INTERRUPTED_RESULT } from "../../core/src/runtime/provider-tool-rounds/contract.js";
  29. import { MessageHistoryImpl } from "../../core/src/agent/message-history.js";
  30. import { hydrateMessageHistoryFromSession } from "../../core/src/agent/session-history-hydrator.js";
  31. import { compactActiveConversation } from "../../core/src/runtime/methods/compact-active.js";
  32. import { buildProviderRequestMessages } from "../../core/src/runtime/helpers/provider-request-messages.js";
  33. import { findLatestCommittedAssistantUsage } from "../../core/src/runtime/methods/turn-model-step-usage.js";
  34. const MODEL_ID = createModelId("GLM-5.3");
  35. const FIXTURE = join(import.meta.dirname, "fixtures", "provider-builtin-analyze-image.sse");
  36. // 服务端新格式(直接下发 mcp_tool_use / mcp_tool_result):由 FIXTURE 按服务端文档改造,其余帧相同。
  37. const MCP_FIXTURE = join(import.meta.dirname, "fixtures", "provider-builtin-analyze-image-mcp.sse");
  38. const TOOL_CALL_ID = "call_93e9e7ad911f4b1799a6c543";
  39. const asIs = (fixture: string) => fixture;
  40. /** 2026-11-05 线上漏发 server_name 的形态:其余帧与 MCP_FIXTURE 相同。 */
  41. function withoutServerName(fixture: string): string {
  42. const edited = fixture.replace('"server_name": "4_5v_mcp", ', "");
  43. if (edited === fixture) throw new Error("MCP fixture has no server_name to drop");
  44. return edited;
  45. }
  46. type WireMessage = { role: string; content: unknown };
  47. type WireBody = { messages: WireMessage[] };
  48. function sse(events: Array<Record<string, unknown>>): Response {
  49. return new Response(
  50. events.map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join(""),
  51. { headers: { "content-type": "text/event-stream" } },
  52. );
  53. }
  54. function plainReply(text: string): Response {
  55. return sse([
  56. {
  57. type: "message_start",
  58. message: {
  59. id: "msg_reply",
  60. type: "message",
  61. role: "assistant",
  62. model: "glm-5.3",
  63. content: [],
  64. stop_reason: null,
  65. stop_sequence: null,
  66. usage: { input_tokens: 10, output_tokens: 0 },
  67. },
  68. },
  69. { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
  70. { type: "content_block_delta", index: 0, delta: { type: "text_delta", text } },
  71. { type: "content_block_stop", index: 0 },
  72. {
  73. type: "message_delta",
  74. delta: { stop_reason: "end_turn", stop_sequence: null },
  75. usage: { output_tokens: 1 },
  76. },
  77. { type: "message_stop" },
  78. ]);
  79. }
  80. function createRuntime(
  81. root: string,
  82. sessionID: SessionId,
  83. store: Awaited<ReturnType<typeof createSqliteSessionStore>>,
  84. events: InMemorySessionEventStore,
  85. ) {
  86. const provider = createRegistryProviderConfig(
  87. parseProviderConfig({
  88. group: "standard-personal",
  89. access: { type: "api-key", apiKey: "fixture-key" },
  90. api: { type: "anthropic-messages", baseUrl: "https://builtin.invalid/v1" },
  91. }),
  92. );
  93. const model = createRegistryModelConfig(
  94. parseModelConfig({
  95. enabled: true,
  96. properties: createTestModelProperties(),
  97. optionSpecs: {
  98. reasoningLevel: { values: ["disabled"], map: "{}" },
  99. maxOutputTokens: { max: 32_000, map: '{"max_tokens": maxOutputTokens}' },
  100. },
  101. }),
  102. );
  103. if (!provider.ok || !model.ok) throw new Error("Invalid model fixture config");
  104. const adapter = new AiSdkModelAdapter({ env: {}, retry: { maxAttempts: 1 } });
  105. return new AgentRuntime(
  106. sessionID,
  107. {
  108. mode: "build",
  109. modelStreaming: "on",
  110. workingDirectory: root,
  111. modelSelection: {
  112. providerId: createModelProviderId("account:zai-individual-coding-plan"),
  113. modelId: MODEL_ID,
  114. options: { reasoningLevel: "disabled" },
  115. },
  116. memory: { enabled: false },
  117. compact: { enabled: false },
  118. },
  119. {
  120. sessionStore: store,
  121. eventStore: events,
  122. modelFactory: ({ selection }) =>
  123. adapter.createModel({
  124. providerId: selection.providerId,
  125. modelId: selection.modelId,
  126. providerConfig: provider.config,
  127. modelConfig: model.config,
  128. options: { maxOutputTokens: 32_000, ...selection.options },
  129. }),
  130. },
  131. );
  132. }
  133. function conversation(body: WireBody | undefined): WireMessage[] {
  134. // 去掉 system 和 cache_control 标记,只比较对话本身。
  135. return JSON.parse(
  136. JSON.stringify((body?.messages ?? []).filter((message) => message.role !== "system")),
  137. (key, value) => (key === "cache_control" ? undefined : value),
  138. );
  139. }
  140. describe("provider built-in tool rounds", () => {
  141. it.each([
  142. ["server_tool_use", FIXTURE, asIs],
  143. ["mcp_tool_use", MCP_FIXTURE, asIs],
  144. // AI SDK schema 要求 server_name,漏发时整轮报错;兼容层补齐后这一轮必须照常完成。
  145. ["mcp_tool_use without server_name", MCP_FIXTURE, withoutServerName],
  146. ])(
  147. "replays a server-executed analyze_image (%s) as its own round, live and after cold resume",
  148. async (_format, fixturePath, edit) => {
  149. const root = await mkdtemp(join(tmpdir(), "zcode-provider-builtin-"));
  150. const sessionID = createSessionId("provider-builtin");
  151. const fixture = edit(await readFile(fixturePath, "utf8"));
  152. const bodies: WireBody[] = [];
  153. let store = await createSqliteSessionStore({ dbPath: join(root, "session.sqlite") });
  154. const events = new InMemorySessionEventStore({ retention: "unbounded" });
  155. let runtime: AgentRuntime | undefined;
  156. try {
  157. vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => {
  158. bodies.push(await new Request(input, init).json());
  159. return bodies.length === 1
  160. ? new Response(fixture, { headers: { "content-type": "text/event-stream" } })
  161. : plainReply(`reply ${bodies.length}`);
  162. });
  163. runtime = createRuntime(root, sessionID, store, events);
  164. await runtime.executeTurn("识别 shot.png 里的文字");
  165. await runtime.executeTurn("再说一遍");
  166. // 下一次请求:服务端工具独立成一轮(方案 A),不再出现 markdown 渲染。
  167. const live = conversation(bodies[1]);
  168. expect(live.map((message) => message.role)).toEqual([
  169. "user",
  170. "assistant",
  171. "user",
  172. "assistant",
  173. "user",
  174. ]);
  175. expect(live[1]!.content).toEqual([
  176. expect.objectContaining({ type: "thinking" }),
  177. { type: "text", text: "图片已上传为远程 URL,现在用视觉分析工具识别其中文字。" },
  178. expect.objectContaining({ type: "tool_use", id: TOOL_CALL_ID, name: "analyze_image" }),
  179. ]);
  180. expect(live[2]!.content).toEqual([
  181. expect.objectContaining({
  182. type: "tool_result",
  183. tool_use_id: TOOL_CALL_ID,
  184. content: expect.stringContaining("Error 1302: request rate limit exceeded"),
  185. }),
  186. ]);
  187. expect(live[3]!.content).toEqual([
  188. { type: "text", text: expect.stringMatching(/^图片中的文字为/) },
  189. ]);
  190. expect(JSON.stringify(bodies[1])).not.toContain("**🌐");
  191. expect(JSON.stringify(bodies[1])).not.toContain("analyze_image_result_summary");
  192. // 持久化按流顺序:本轮正文 → 服务端工具卡片 → 下一轮正文。
  193. const assistant = (await store.messages({ sessionID })).find(
  194. (message) => message.info.role === "assistant",
  195. );
  196. const parts = assistant!.parts.filter(
  197. (part) => part.type !== "step-start" && part.type !== "step-finish",
  198. );
  199. expect(parts.map((part) => part.type)).toEqual(["reasoning", "text", "tool", "text"]);
  200. expect(parts[2]).toMatchObject({
  201. type: "tool",
  202. callID: TOOL_CALL_ID,
  203. tool: "analyze_image",
  204. metadata: { providerExecuted: true },
  205. state: { status: "completed", output: expect.stringContaining("Order Console") },
  206. });
  207. // 实时卡片:Scheduled → Started → Result,结果是服务端返回的识别文本。
  208. const toolEvents = (await events.getEvents(sessionID)).filter(
  209. (event) =>
  210. (event.payload as { toolCallId?: string } | undefined)?.toolCallId === TOOL_CALL_ID &&
  211. event.type !== SessionEventType.ModelStreaming,
  212. );
  213. expect(toolEvents.map((event) => event.type)).toEqual([
  214. SessionEventType.ToolCallScheduled,
  215. SessionEventType.ToolCallStarted,
  216. SessionEventType.ToolCallResult,
  217. ]);
  218. // 冷恢复后回放出完全相同的对话。
  219. runtime.beginShutdown();
  220. store.close();
  221. store = await createSqliteSessionStore({ dbPath: join(root, "session.sqlite") });
  222. runtime = createRuntime(
  223. root,
  224. sessionID,
  225. store,
  226. new InMemorySessionEventStore({ retention: "unbounded" }),
  227. );
  228. await runtime.resumeFromStore();
  229. await runtime.executeTurn("第三句");
  230. const cold = conversation(bodies[2]);
  231. expect(cold.slice(0, live.length + 1)).toEqual([
  232. ...live,
  233. { role: "assistant", content: [{ type: "text", text: "reply 2" }] },
  234. ]);
  235. } finally {
  236. runtime?.beginShutdown();
  237. vi.unstubAllGlobals();
  238. store.close();
  239. await rm(root, { recursive: true, force: true });
  240. }
  241. },
  242. );
  243. });
  244. // ─── 评审回归:终态判断、断流作废、缺少结果 ────────────────────────────────────
  245. function fixtureFrames(fixture: string): string[] {
  246. return fixture.split("\n\n").filter((frame) => frame.trim().length > 0);
  247. }
  248. function frameData(frame: string): Record<string, unknown> | undefined {
  249. const line = frame.split("\n").find((candidate) => candidate.startsWith("data:"));
  250. return line ? (JSON.parse(line.slice("data:".length)) as Record<string, unknown>) : undefined;
  251. }
  252. function sseBody(frames: string[]): string {
  253. return frames.map((frame) => `${frame}\n\n`).join("");
  254. }
  255. function eventStream(body: string): Response {
  256. return new Response(body, { headers: { "content-type": "text/event-stream" } });
  257. }
  258. async function openScenario(
  259. respond: (index: number, fixture: string, body: WireBody) => Response,
  260. fixturePath = FIXTURE,
  261. ) {
  262. const root = await mkdtemp(join(tmpdir(), "zcode-provider-builtin-"));
  263. const sessionID = createSessionId("provider-builtin-regression");
  264. const fixture = await readFile(fixturePath, "utf8");
  265. const bodies: WireBody[] = [];
  266. const dbPath = join(root, "session.sqlite");
  267. let store = await createSqliteSessionStore({ dbPath });
  268. const events = new InMemorySessionEventStore({ retention: "unbounded" });
  269. vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => {
  270. const body = (await new Request(input, init).json()) as WireBody;
  271. bodies.push(body);
  272. return respond(bodies.length - 1, fixture, body);
  273. });
  274. let runtime = createRuntime(root, sessionID, store, events);
  275. return {
  276. bodies,
  277. events,
  278. sessionID,
  279. get store() {
  280. return store;
  281. },
  282. get runtime() {
  283. return runtime;
  284. },
  285. async coldResume() {
  286. runtime.beginShutdown();
  287. store.close();
  288. store = await createSqliteSessionStore({ dbPath });
  289. runtime = createRuntime(
  290. root,
  291. sessionID,
  292. store,
  293. new InMemorySessionEventStore({ retention: "unbounded" }),
  294. );
  295. await runtime.resumeFromStore();
  296. },
  297. async close() {
  298. runtime.beginShutdown();
  299. vi.unstubAllGlobals();
  300. store.close();
  301. await rm(root, { recursive: true, force: true });
  302. },
  303. };
  304. }
  305. /** 再发一句拿 live history,冷恢复后再发一句拿冷恢复 history,两者必须一致。 */
  306. async function expectColdResumeMatchesLive(scenario: Awaited<ReturnType<typeof openScenario>>) {
  307. await scenario.runtime.executeTurn("再说一遍");
  308. const live = conversation(scenario.bodies.at(-1));
  309. await scenario.coldResume();
  310. await scenario.runtime.executeTurn("第三句");
  311. const cold = conversation(scenario.bodies.at(-1));
  312. expect(cold.slice(0, live.length)).toEqual(live);
  313. return live;
  314. }
  315. describe("provider built-in tool rounds (review regressions)", () => {
  316. const formats = [
  317. ["server_tool_use", FIXTURE],
  318. ["mcp_tool_use", MCP_FIXTURE],
  319. ];
  320. it.each(formats)(
  321. "still continues a truncated answer after a server-executed tool round (%s)",
  322. async (_format, fixturePath) => {
  323. const scenario = await openScenario(
  324. (index, fixture) =>
  325. index === 0
  326. ? eventStream(
  327. fixture.replace(/"stop_reason": "end_turn"/u, '"stop_reason": "max_tokens"'),
  328. )
  329. : plainReply(`reply ${index}`),
  330. fixturePath,
  331. );
  332. try {
  333. await scenario.runtime.executeTurn("识别 shot.png 里的文字");
  334. // 服务端工具不算待执行调用:max_tokens 必须触发续写请求。
  335. expect(scenario.bodies).toHaveLength(2);
  336. const continuation = conversation(scenario.bodies[1]);
  337. expect(JSON.stringify(continuation.at(-1))).toContain(OUTPUT_TOKEN_CONTINUE_PROMPT);
  338. expect(continuation.some((message) => JSON.stringify(message).includes(TOOL_CALL_ID))).toBe(
  339. true,
  340. );
  341. } finally {
  342. await scenario.close();
  343. }
  344. },
  345. );
  346. it.each(formats)(
  347. "keeps a discarded stream attempt out of both live and cold-resumed history (%s)",
  348. async (_format, fixturePath) => {
  349. const scenario = await openScenario((index, fixture) => {
  350. if (index !== 0) return plainReply(`reply ${index}`);
  351. // 服务端工具与结果已下发、最后一轮正文写到一半时断流(可重试)。
  352. const frames = fixtureFrames(fixture);
  353. const cut = frames.findIndex((frame) => {
  354. const data = frameData(frame);
  355. return data?.type === "content_block_delta" && data.index === 6;
  356. });
  357. const encoder = new TextEncoder();
  358. let delivered = false;
  359. return new Response(
  360. new ReadableStream<Uint8Array>({
  361. // 先交付已收到的帧,等下游消费后再断流:源流出错时,下游 TransformStream 里尚未读取的数据会被丢弃。
  362. async pull(controller) {
  363. if (!delivered) {
  364. delivered = true;
  365. controller.enqueue(encoder.encode(sseBody(frames.slice(0, cut + 1))));
  366. return;
  367. }
  368. await new Promise((resolve) => setTimeout(resolve, 50));
  369. // 与 Node 真实 socket 错误一致带 code,adapter 才会归类为网络断流。
  370. controller.error(Object.assign(new Error("read ECONNRESET"), { code: "ECONNRESET" }));
  371. },
  372. }),
  373. { headers: { "content-type": "text/event-stream" } },
  374. );
  375. }, fixturePath);
  376. try {
  377. await scenario.runtime.executeTurn("识别 shot.png 里的文字");
  378. const live = await expectColdResumeMatchesLive(scenario);
  379. // 作废的 attempt 不进任何 history:只剩重试后的回答。
  380. expect(JSON.stringify(live)).not.toContain(TOOL_CALL_ID);
  381. expect(live.map((message) => message.role)).toEqual(["user", "assistant", "user"]);
  382. } finally {
  383. await scenario.close();
  384. }
  385. },
  386. );
  387. it("drops an MCP result that no call paired and settles the call as interrupted, live and cold", async () => {
  388. // AI SDK 遇到未配对的 mcp_tool_result 会抛 TypeError,整轮失败;兼容层丢弃它后,调用按中断收口。
  389. const scenario = await openScenario(
  390. (index, fixture) =>
  391. index === 0
  392. ? eventStream(
  393. fixture.replace(`"tool_use_id": "${TOOL_CALL_ID}"`, '"tool_use_id": "call_unpaired"'),
  394. )
  395. : plainReply(`reply ${index}`),
  396. MCP_FIXTURE,
  397. );
  398. try {
  399. await scenario.runtime.executeTurn("识别 shot.png 里的文字");
  400. const live = await expectColdResumeMatchesLive(scenario);
  401. expect(live[2]!.content).toEqual([
  402. expect.objectContaining({
  403. type: "tool_result",
  404. tool_use_id: TOOL_CALL_ID,
  405. is_error: true,
  406. content: PROVIDER_TOOL_INTERRUPTED_RESULT,
  407. }),
  408. ]);
  409. } finally {
  410. await scenario.close();
  411. }
  412. });
  413. // 新格式合成流:调用、结果和文字块按服务端文档的形态构造。
  414. const textEvents = (index: number, value: string) => [
  415. { type: "content_block_start", index, content_block: { type: "text", text: "" } },
  416. { type: "content_block_delta", index, delta: { type: "text_delta", text: value } },
  417. { type: "content_block_stop", index },
  418. ];
  419. const mcpCallEvents = (index: number, id: string, name: string) => [
  420. {
  421. type: "content_block_start",
  422. index,
  423. content_block: { type: "mcp_tool_use", id, name, server_name: "4_5v_mcp", input: { name } },
  424. },
  425. { type: "content_block_stop", index },
  426. ];
  427. const mcpResultEvents = (index: number, id: string, value: string, isError: boolean) => [
  428. {
  429. type: "content_block_start",
  430. index,
  431. content_block: {
  432. type: "mcp_tool_result",
  433. tool_use_id: id,
  434. content: [{ type: "text", text: value }],
  435. is_error: isError,
  436. },
  437. },
  438. { type: "content_block_stop", index },
  439. ];
  440. const mcpReply = (blocks: Array<Record<string, unknown>>) =>
  441. sse([
  442. {
  443. type: "message_start",
  444. message: {
  445. id: "msg_mcp",
  446. type: "message",
  447. role: "assistant",
  448. model: "glm-5.3",
  449. content: [],
  450. stop_reason: null,
  451. stop_sequence: null,
  452. usage: { input_tokens: 10, output_tokens: 0 },
  453. },
  454. },
  455. ...blocks,
  456. {
  457. type: "message_delta",
  458. delta: { stop_reason: "end_turn", stop_sequence: null },
  459. usage: { output_tokens: 1 },
  460. },
  461. { type: "message_stop" },
  462. ]);
  463. it("keeps a model answer labelled **Output:** when the server sends no summary, live and cold", async () => {
  464. // 评审 CR-01:结果后没有服务端摘要,模型回答以 **Output:** 开头;兼容层不能把整段回答删掉。
  465. const answer = "**Output:** 正常最终回答";
  466. const scenario = await openScenario((index) =>
  467. index === 0
  468. ? mcpReply([
  469. ...mcpCallEvents(0, "call_a", "analyze_image"),
  470. ...mcpResultEvents(1, "call_a", "图片结果", false),
  471. ...textEvents(2, answer),
  472. ])
  473. : plainReply(`reply ${index}`),
  474. );
  475. try {
  476. await scenario.runtime.executeTurn("看图");
  477. const assistant = (await scenario.store.messages({ sessionID: scenario.sessionID })).find(
  478. (message) => message.info.role === "assistant",
  479. );
  480. expect(assistant!.parts).toContainEqual(
  481. expect.objectContaining({ type: "text", text: answer }),
  482. );
  483. const live = await expectColdResumeMatchesLive(scenario);
  484. expect(live[3]!.content).toEqual([{ type: "text", text: answer }]);
  485. } finally {
  486. await scenario.close();
  487. }
  488. });
  489. it("replays parallel MCP calls, including an error result, as rounds in call order, live and cold", async () => {
  490. // 新格式并行:调用都在前、结果都在后,按 id 配对回各自的轮次;方案 A 回放成先后两轮。
  491. const scenario = await openScenario((index) =>
  492. index === 0
  493. ? mcpReply([
  494. ...textEvents(0, "**🌐 Built-in Tool: analyze_image**"),
  495. ...mcpCallEvents(1, "call_a", "analyze_image"),
  496. ...textEvents(2, "**🌐 Built-in Tool: webReader**"),
  497. ...mcpCallEvents(3, "call_b", "webReader"),
  498. ...mcpResultEvents(4, "call_a", "图片结果", false),
  499. ...textEvents(5, "**Output:**\n**analyze_image_result_summary:** 图片结果"),
  500. ...mcpResultEvents(6, "call_b", "MCP error 400", true),
  501. ...textEvents(7, "**Output:**\n**webReader_result_summary:** MCP error 400"),
  502. ...textEvents(8, "最终回答"),
  503. ])
  504. : plainReply(`reply ${index}`),
  505. );
  506. try {
  507. await scenario.runtime.executeTurn("看图并读网页");
  508. const toolEvents = (await scenario.events.getEvents(scenario.sessionID)).filter(
  509. (event) =>
  510. ["call_a", "call_b"].includes(
  511. (event.payload as { toolCallId?: string } | undefined)?.toolCallId ?? "",
  512. ) && event.type !== SessionEventType.ModelStreaming,
  513. );
  514. expect(
  515. toolEvents.map((event) => [
  516. event.type,
  517. (event.payload as { toolCallId: string }).toolCallId,
  518. ]),
  519. ).toEqual([
  520. [SessionEventType.ToolCallScheduled, "call_a"],
  521. [SessionEventType.ToolCallStarted, "call_a"],
  522. [SessionEventType.ToolCallScheduled, "call_b"],
  523. [SessionEventType.ToolCallStarted, "call_b"],
  524. [SessionEventType.ToolCallResult, "call_a"],
  525. [SessionEventType.ToolCallResult, "call_b"],
  526. ]);
  527. expect(toolEvents.at(-1)!.payload).toMatchObject({ result: { success: false } });
  528. const live = await expectColdResumeMatchesLive(scenario);
  529. const wire = JSON.stringify(live);
  530. expect(wire).not.toContain("**🌐");
  531. expect(wire).not.toContain("**Output:**");
  532. expect(live.map((message) => message.role)).toEqual([
  533. "user",
  534. "assistant",
  535. "user",
  536. "assistant",
  537. "user",
  538. "assistant",
  539. "user",
  540. ]);
  541. expect(live[1]!.content).toEqual([
  542. expect.objectContaining({ type: "tool_use", id: "call_a", name: "analyze_image" }),
  543. ]);
  544. expect(live[2]!.content).toEqual([
  545. expect.objectContaining({
  546. type: "tool_result",
  547. tool_use_id: "call_a",
  548. content: "图片结果",
  549. }),
  550. ]);
  551. expect(live[3]!.content).toEqual([
  552. expect.objectContaining({ type: "tool_use", id: "call_b", name: "webReader" }),
  553. ]);
  554. expect(live[4]!.content).toEqual([
  555. expect.objectContaining({
  556. type: "tool_result",
  557. tool_use_id: "call_b",
  558. is_error: true,
  559. content: "MCP error 400",
  560. }),
  561. ]);
  562. expect(live[5]!.content).toEqual([{ type: "text", text: "最终回答" }]);
  563. } finally {
  564. await scenario.close();
  565. }
  566. });
  567. it("settles a server tool whose result never arrives as interrupted, live and cold", async () => {
  568. const scenario = await openScenario((index, fixture) => {
  569. if (index !== 0) return plainReply(`reply ${index}`);
  570. const frames = fixtureFrames(fixture).filter((frame) => {
  571. const data = frameData(frame);
  572. const block = data?.content_block as { type?: string } | undefined;
  573. return !(
  574. (data?.type === "content_block_start" && block?.type === "tool_result") ||
  575. (data?.type === "content_block_stop" && data.index === 5)
  576. );
  577. });
  578. return eventStream(sseBody(frames));
  579. });
  580. try {
  581. await scenario.runtime.executeTurn("识别 shot.png 里的文字");
  582. const toolEvents = (await scenario.events.getEvents(scenario.sessionID)).filter(
  583. (event) =>
  584. (event.payload as { toolCallId?: string } | undefined)?.toolCallId === TOOL_CALL_ID &&
  585. event.type !== SessionEventType.ModelStreaming,
  586. );
  587. expect(toolEvents.map((event) => event.type)).toEqual([
  588. SessionEventType.ToolCallScheduled,
  589. SessionEventType.ToolCallStarted,
  590. SessionEventType.ToolCallResult,
  591. ]);
  592. expect(toolEvents[2]!.payload).toMatchObject({ result: { success: false } });
  593. const live = await expectColdResumeMatchesLive(scenario);
  594. expect(live[2]!.content).toEqual([
  595. expect.objectContaining({
  596. type: "tool_result",
  597. tool_use_id: TOOL_CALL_ID,
  598. is_error: true,
  599. content: PROVIDER_TOOL_INTERRUPTED_RESULT,
  600. }),
  601. ]);
  602. } finally {
  603. await scenario.close();
  604. }
  605. });
  606. it("keeps one compact group per stored response, live and after cold resume", async () => {
  607. const scenario = await openScenario((_index, fixture, body) => {
  608. const text = JSON.stringify(body.messages);
  609. if (text.includes("create a detailed summary")) {
  610. return plainReply("<summary>older work summary</summary>");
  611. }
  612. return text.includes("识别 shot.png") && !text.includes(TOOL_CALL_ID)
  613. ? eventStream(fixture)
  614. : plainReply("earlier reply");
  615. });
  616. try {
  617. await scenario.runtime.executeTurn("old setup");
  618. await scenario.runtime.executeTurn("识别 shot.png 里的文字");
  619. // 一条持久化 assistant 拆成了 round + 最后一轮;compact 保留最近一组时必须整条保留或整条摘要。
  620. await compactActiveConversation.call(
  621. scenario.runtime as never,
  622. undefined,
  623. createRootTraceContext({ sessionId: scenario.sessionID }),
  624. [],
  625. { trigger: CompactTrigger.Auto },
  626. );
  627. const project = (entries: ReturnType<MessageHistoryImpl["toRuntimeEntries"]>) =>
  628. buildProviderRequestMessages({
  629. entries,
  630. useMidConversationSystem: false,
  631. applyCacheControl: false,
  632. }).messages.filter((message) => message.toolCalls?.length || message.role === "tool");
  633. const live = project(
  634. (
  635. scenario.runtime as unknown as { messageHistory: MessageHistoryImpl }
  636. ).messageHistory.toRuntimeEntries(),
  637. );
  638. const restored = new MessageHistoryImpl();
  639. await hydrateMessageHistoryFromSession({
  640. history: restored,
  641. messages: await scenario.store.messages({ sessionID: scenario.sessionID }),
  642. });
  643. expect(project(restored.toRuntimeEntries())).toEqual(live);
  644. // 最近一组是整条服务端工具响应:调用与结果随最后一轮一起保留。
  645. expect(JSON.stringify(live)).toContain(TOOL_CALL_ID);
  646. } finally {
  647. await scenario.close();
  648. }
  649. });
  650. it("keeps two responses that reuse a server tool call id in separate compact groups", async () => {
  651. // 工具调用 id 只保证单次响应内配对:两次响应都用同一个 id 时,compact 分组仍必须按持久化消息分开。
  652. const scenario = await openScenario((_index, fixture, body) => {
  653. if (JSON.stringify(body.messages).includes("create a detailed summary")) {
  654. return plainReply("<summary>older work summary</summary>");
  655. }
  656. return JSON.stringify(body.messages.at(-1)).includes("识别")
  657. ? eventStream(fixture)
  658. : plainReply("earlier reply");
  659. });
  660. try {
  661. await scenario.runtime.executeTurn("old setup");
  662. await scenario.runtime.executeTurn("识别 shot.png 里的文字");
  663. await scenario.runtime.executeTurn("再识别一次 shot.png");
  664. await compactActiveConversation.call(
  665. scenario.runtime as never,
  666. undefined,
  667. createRootTraceContext({ sessionId: scenario.sessionID }),
  668. [],
  669. { trigger: CompactTrigger.Auto },
  670. );
  671. const project = (entries: ReturnType<MessageHistoryImpl["toRuntimeEntries"]>) =>
  672. buildProviderRequestMessages({
  673. entries,
  674. useMidConversationSystem: false,
  675. applyCacheControl: false,
  676. }).messages.filter((message) => message.toolCalls?.length || message.role === "tool");
  677. const live = project(
  678. (
  679. scenario.runtime as unknown as { messageHistory: MessageHistoryImpl }
  680. ).messageHistory.toRuntimeEntries(),
  681. );
  682. const restored = new MessageHistoryImpl();
  683. await hydrateMessageHistoryFromSession({
  684. history: restored,
  685. messages: await scenario.store.messages({ sessionID: scenario.sessionID }),
  686. });
  687. expect(project(restored.toRuntimeEntries())).toEqual(live);
  688. // 只保留最近一次响应:一次服务端调用加它的结果,而不是两次响应合并成的一组。
  689. expect(live.map((message) => message.role)).toEqual(["assistant", "tool"]);
  690. } finally {
  691. await scenario.close();
  692. }
  693. });
  694. it.each(["with", "without"] as const)(
  695. "does not anchor context usage on a server tool response %s trailing text, live and cold",
  696. async (trailing) => {
  697. // 服务端多轮请求的 usage 是合计(fixture 约 37k,单次上下文约一半),不能当估算锚点。
  698. const fixtureFor = (fixture: string) =>
  699. trailing === "with"
  700. ? fixture
  701. : sseBody(fixtureFrames(fixture).filter((frame) => frameData(frame)?.index !== 6));
  702. const scenario = await openScenario((_index, fixture, body) => {
  703. const text = JSON.stringify(body.messages);
  704. return text.includes("识别 shot.png") && !text.includes(TOOL_CALL_ID)
  705. ? eventStream(fixtureFor(fixture))
  706. : plainReply("earlier reply");
  707. });
  708. try {
  709. await scenario.runtime.executeTurn("old setup");
  710. await scenario.runtime.executeTurn("识别 shot.png 里的文字");
  711. const anchorOf = (entries: ReturnType<MessageHistoryImpl["toRuntimeEntries"]>) => {
  712. const anchor = findLatestCommittedAssistantUsage(entries);
  713. const entry = anchor ? entries[anchor.messageIndex] : undefined;
  714. return {
  715. baseline: anchor?.baseline,
  716. message: entry && "message" in entry ? entry.message.content : undefined,
  717. };
  718. };
  719. const live = anchorOf(
  720. (
  721. scenario.runtime as unknown as { messageHistory: MessageHistoryImpl }
  722. ).messageHistory.toRuntimeEntries(),
  723. );
  724. const restored = new MessageHistoryImpl();
  725. await hydrateMessageHistoryFromSession({
  726. history: restored,
  727. messages: await scenario.store.messages({ sessionID: scenario.sessionID }),
  728. });
  729. expect(anchorOf(restored.toRuntimeEntries())).toEqual(live);
  730. // 锚点仍是上一轮的真实 usage,而不是服务端合计。
  731. expect(JSON.stringify(live.message)).toContain("earlier reply");
  732. await expectColdResumeMatchesLive(scenario);
  733. } finally {
  734. await scenario.close();
  735. }
  736. },
  737. );
  738. });