provider-request-messages.test.ts 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710
  1. import { describe, expect, it } from "vitest";
  2. import type { ModelInputMessage, RuntimeMessageEntry } from "../src/agent/message-history.js";
  3. import {
  4. realUserRuntimeMetadata,
  5. systemReminderRuntimeMetadata,
  6. } from "../src/agent/message-history.js";
  7. import { buildProviderRequestMessages } from "../src/runtime/helpers/provider-request-messages.js";
  8. import { buildRuntimeProviderRequestMessages } from "../src/runtime/helpers/runtime-provider-request-messages.js";
  9. import { createTestRuntimeModel } from "./test-runtime-model.js";
  10. function entry(
  11. message: ModelInputMessage,
  12. source?: RuntimeMessageEntry["metadata"]["source"],
  13. ): RuntimeMessageEntry {
  14. return {
  15. message,
  16. metadata: source ? { source } : undefined,
  17. };
  18. }
  19. function attachment(
  20. source: RuntimeMessageEntry["metadata"]["source"],
  21. content: string,
  22. ): RuntimeMessageEntry {
  23. return {
  24. kind: "attachment",
  25. content,
  26. metadata: { source },
  27. };
  28. }
  29. function user(content: ModelInputMessage["content"]): ModelInputMessage {
  30. return { role: "user", content };
  31. }
  32. function assistant(content = "assistant"): ModelInputMessage {
  33. return { role: "assistant", content };
  34. }
  35. function toolResultUser(content = "tool result"): ModelInputMessage {
  36. return {
  37. role: "user",
  38. content: [{ type: "text", text: content }],
  39. toolCallId: "tool-1",
  40. toolName: "Read",
  41. };
  42. }
  43. function toolResult(
  44. content = "tool result",
  45. toolCallId = "tool-1",
  46. toolName = "Read",
  47. ): ModelInputMessage {
  48. return {
  49. role: "tool",
  50. content,
  51. toolCallId,
  52. toolName,
  53. };
  54. }
  55. // 折叠只在 Anthropic Messages 协议打开,由模型请求能力决定。
  56. const FOLD = { foldRemindersIntoToolResults: true } as const;
  57. function providerText(message: ModelInputMessage): string {
  58. return typeof message.content === "string"
  59. ? message.content
  60. : message.content.map((block) => (block.type === "text" ? block.text : "")).join("");
  61. }
  62. function deepFreeze<T>(value: T): T {
  63. if (value && typeof value === "object") {
  64. Object.freeze(value);
  65. for (const nested of Object.values(value as Record<string, unknown>)) {
  66. deepFreeze(nested);
  67. }
  68. }
  69. return value;
  70. }
  71. describe("buildProviderRequestMessages", () => {
  72. it("keeps committed assistant entry ownership separate from provider messages", () => {
  73. const assistant = {
  74. message: { role: "assistant" as const, content: "answer" },
  75. tokens: { input: 100, output: 20, reasoning: 0, cache: { read: 0, write: 0 }, total: 120 },
  76. } satisfies RuntimeMessageEntry;
  77. const entries = [entry(user("prompt"), "real_user"), assistant] satisfies RuntimeMessageEntry[];
  78. const result = buildProviderRequestMessages({ entries });
  79. expect(result.messages).toEqual([
  80. { role: "user", content: "prompt" },
  81. { role: "assistant", content: "answer" },
  82. ]);
  83. expect(result.sourceEntries).toEqual([entries[0], assistant]);
  84. });
  85. it("keeps a persisted Continue provider-visible without moving the latest real user", () => {
  86. const entries = [
  87. entry(user("real prompt"), "real_user"),
  88. entry(assistant("partial")),
  89. entry(user("continue locally"), "output_token_continuation"),
  90. ] satisfies RuntimeMessageEntry[];
  91. const result = buildProviderRequestMessages({ entries });
  92. expect(result.messages).toEqual([
  93. user("real prompt"),
  94. assistant("partial"),
  95. user("continue locally"),
  96. ]);
  97. expect(result.diagnostics.latestRealUserMessageIndex).toBe(0);
  98. });
  99. it("projects structured system reminder attachments using raw body content", () => {
  100. const entries = [
  101. entry(user("real prompt"), "real_user"),
  102. attachment("output_style", "style body"),
  103. ] satisfies RuntimeMessageEntry[];
  104. const result = buildProviderRequestMessages({ entries, applyCacheControl: true });
  105. expect(result.messages).toEqual([
  106. { role: "user", content: "real prompt", cacheControl: { type: "ephemeral" } },
  107. { role: "system", content: "style body" },
  108. ]);
  109. });
  110. it("projects structured prompt attachments as mid-conversation system messages", () => {
  111. const entries = [
  112. entry(user("Summarize notes."), "real_user"),
  113. attachment(
  114. "prompt_attachment",
  115. 'Called the Read tool with the following input: {"file_path":"notes.md"}',
  116. ),
  117. attachment("prompt_attachment", "Result of calling the Read tool:\n1\t# Notes"),
  118. ] satisfies RuntimeMessageEntry[];
  119. const result = buildProviderRequestMessages({ entries });
  120. expect(result.messages).toEqual([
  121. { role: "user", content: "Summarize notes." },
  122. {
  123. role: "system",
  124. content:
  125. 'Called the Read tool with the following input: {"file_path":"notes.md"}\n\nResult of calling the Read tool:\n1\t# Notes',
  126. },
  127. ]);
  128. });
  129. it("projects MCS-capable attachments as system messages when MCS is explicitly enabled", () => {
  130. const entries = [
  131. entry(user("Summarize notes."), "real_user"),
  132. attachment("prompt_attachment", "Called the Read tool with the following input: {}"),
  133. attachment("output_style", "Terse output style is active."),
  134. ] satisfies RuntimeMessageEntry[];
  135. expect(
  136. buildProviderRequestMessages({
  137. entries,
  138. useMidConversationSystem: true,
  139. }).messages,
  140. ).toEqual([
  141. { role: "user", content: "Summarize notes." },
  142. {
  143. role: "system",
  144. content:
  145. "Called the Read tool with the following input: {}\n\nTerse output style is active.",
  146. },
  147. ]);
  148. });
  149. it("projects goal state changes as mid-conversation system messages when MCS is enabled", () => {
  150. const entries = [
  151. entry(user("Continue"), "real_user"),
  152. attachment(
  153. "goal_state_change",
  154. "The active session goal is paused. Do not continue pursuing it unless the user resumes or replaces the goal.",
  155. ),
  156. ] satisfies RuntimeMessageEntry[];
  157. expect(
  158. buildProviderRequestMessages({
  159. entries,
  160. useMidConversationSystem: true,
  161. }).messages,
  162. ).toEqual([
  163. { role: "user", content: "Continue" },
  164. {
  165. role: "system",
  166. content:
  167. "The active session goal is paused. Do not continue pursuing it unless the user resumes or replaces the goal.",
  168. },
  169. ]);
  170. });
  171. it("falls back goal state changes to user system reminders when MCS is disabled", () => {
  172. const entries = [
  173. entry(user("Continue"), "real_user"),
  174. attachment(
  175. "goal_state_change",
  176. "The session goal has been cleared. Do not continue pursuing any previous goal unless the user sets a new goal.",
  177. ),
  178. ] satisfies RuntimeMessageEntry[];
  179. expect(
  180. buildProviderRequestMessages({
  181. entries,
  182. useMidConversationSystem: false,
  183. }).messages,
  184. ).toEqual([
  185. { role: "user", content: "Continue" },
  186. {
  187. role: "user",
  188. content:
  189. "<system-reminder>\nThe session goal has been cleared. Do not continue pursuing any previous goal unless the user sets a new goal.\n</system-reminder>",
  190. },
  191. ]);
  192. });
  193. it("does not bubble a goal state change before an older target continuation", () => {
  194. const pauseReminder =
  195. "The active session goal is paused. Do not continue pursuing it unless the user resumes or replaces the goal.";
  196. const entries = [
  197. entry(user("Original goal"), "real_user"),
  198. entry(user("Continue working toward the active session goal."), "target_continuation"),
  199. attachment("goal_state_change", pauseReminder),
  200. entry(user("Follow-up after Stop"), "real_user"),
  201. ] satisfies RuntimeMessageEntry[];
  202. const result = buildProviderRequestMessages({
  203. entries,
  204. useMidConversationSystem: false,
  205. });
  206. expect(result.messages).toEqual([
  207. { role: "user", content: "Original goal" },
  208. { role: "user", content: "Continue working toward the active session goal." },
  209. {
  210. role: "user",
  211. content: `<system-reminder>\n${pauseReminder}\n</system-reminder>`,
  212. },
  213. { role: "user", content: "Follow-up after Stop" },
  214. ]);
  215. expect(result.diagnostics.bubbledAttachmentEntryCount).toBe(0);
  216. });
  217. it("renders MCS-capable attachments as legacy user system reminders when MCS is disabled", () => {
  218. const entries = [
  219. entry(user("Summarize notes."), "real_user"),
  220. attachment("prompt_attachment", "Called the Read tool with the following input: {}"),
  221. ] satisfies RuntimeMessageEntry[];
  222. expect(
  223. buildProviderRequestMessages({
  224. entries,
  225. useMidConversationSystem: false,
  226. }).messages,
  227. ).toEqual([
  228. {
  229. role: "user",
  230. content:
  231. "<system-reminder>\nCalled the Read tool with the following input: {}\n</system-reminder>",
  232. },
  233. { role: "user", content: "Summarize notes." },
  234. ]);
  235. });
  236. it("applies attachment bubble ordering before MCS projection", () => {
  237. const entries = [
  238. entry(user("Real query"), "real_user"),
  239. attachment("output_style", "Style body"),
  240. entry(assistant("Answer")),
  241. ] satisfies RuntimeMessageEntry[];
  242. const legacy = buildProviderRequestMessages({
  243. entries,
  244. useMidConversationSystem: false,
  245. }).messages;
  246. expect(legacy.map((message) => message.role)).toEqual(["user", "user", "assistant"]);
  247. expect(String(legacy[0]?.content)).toContain("Style body");
  248. expect(legacy[1]?.content).toBe("Real query");
  249. const mcs = buildProviderRequestMessages({
  250. entries,
  251. useMidConversationSystem: true,
  252. });
  253. expect(mcs.messages.map((message) => message.role)).toEqual(["user", "system", "assistant"]);
  254. expect(mcs.messages[0]?.content).toBe("Real query");
  255. expect(mcs.messages[1]?.content).toBe("Style body");
  256. expect(mcs.diagnostics.bubbledAttachmentEntryCount).toBe(1);
  257. });
  258. it("keeps target verifier prompts as plain user messages while projecting history attachments", () => {
  259. const entries = [
  260. entry(user("original goal turn"), "real_user"),
  261. attachment("output_style", "Use verifier style."),
  262. entry(user("Verify whether the active goal is complete.")),
  263. ] satisfies RuntimeMessageEntry[];
  264. const result = buildProviderRequestMessages({ entries, applyCacheControl: true });
  265. expect(result.messages).toEqual([
  266. { role: "user", content: "original goal turn" },
  267. {
  268. role: "user",
  269. content: "Verify whether the active goal is complete.",
  270. cacheControl: { type: "ephemeral" },
  271. },
  272. {
  273. role: "system",
  274. content: "Use verifier style.",
  275. },
  276. ]);
  277. });
  278. it("does not project legacy message entries just because their source is eligible", () => {
  279. const entries = [
  280. entry(user("real prompt"), "real_user"),
  281. entry(user("style body"), "output_style"),
  282. entry(user("<system-reminder>\ntodo\n</system-reminder>"), "todo_reminder"),
  283. ] satisfies RuntimeMessageEntry[];
  284. const result = buildProviderRequestMessages({ entries });
  285. expect(result.messages).toEqual([
  286. { role: "user", content: "real prompt" },
  287. { role: "user", content: "style body" },
  288. { role: "user", content: "<system-reminder>\ntodo\n</system-reminder>" },
  289. ]);
  290. });
  291. it("moves skills listing after the first real user as a system message", () => {
  292. const entries = [
  293. entry({ role: "system", content: "prefix" }),
  294. attachment("skills_listing", "skills"),
  295. attachment("context_prefix", "# currentDate\nToday"),
  296. entry(user("real prompt"), "real_user"),
  297. ] satisfies RuntimeMessageEntry[];
  298. const result = buildProviderRequestMessages({ entries, applyCacheControl: true });
  299. expect(result.messages).toEqual([
  300. { role: "system", content: "prefix" },
  301. {
  302. role: "user",
  303. content: "<system-reminder>\n# currentDate\nToday\n</system-reminder>",
  304. },
  305. {
  306. role: "user",
  307. content: "real prompt",
  308. cacheControl: { type: "ephemeral" },
  309. },
  310. { role: "system", content: "skills" },
  311. ]);
  312. expect(result.diagnostics.cacheControlIndex).toBe(2);
  313. expect(result.diagnostics.latestRealUserMessageIndex).toBe(2);
  314. });
  315. it("ends the user text right before a real user input with a newline", () => {
  316. const entries = [
  317. attachment("context_prefix", "instructions"),
  318. attachment("session_context", "git"),
  319. entry(user("real prompt"), "real_user"),
  320. entry(assistant("answer")),
  321. entry(toolResultUser("tool output")),
  322. entry(user("next prompt"), "real_user"),
  323. ] satisfies RuntimeMessageEntry[];
  324. const result = buildProviderRequestMessages({
  325. entries,
  326. useMidConversationSystem: false,
  327. ...FOLD,
  328. });
  329. expect(result.messages.map((message) => message.content)).toEqual([
  330. "<system-reminder>\ninstructions\n</system-reminder>",
  331. "<system-reminder>\ngit\n</system-reminder>\n",
  332. "real prompt",
  333. "answer",
  334. [{ type: "text", text: "tool output" }],
  335. "next prompt",
  336. ]);
  337. });
  338. it("ends the user text right before a compact summary with a newline", () => {
  339. const summary: RuntimeMessageEntry = {
  340. message: user("This session is being continued from a previous conversation."),
  341. metadata: { source: "legacy_synthetic", compactBoundary: { boundaryId: "b1" } },
  342. };
  343. const entries = [
  344. attachment("context_prefix", "instructions"),
  345. attachment("session_context", "git"),
  346. summary,
  347. entry(assistant("kept answer")),
  348. ] satisfies RuntimeMessageEntry[];
  349. const result = buildProviderRequestMessages({
  350. entries,
  351. useMidConversationSystem: false,
  352. ...FOLD,
  353. });
  354. // summary 与真实输入一样,前一条 user 文本以换行结尾。
  355. expect(result.messages[1]?.content).toBe("<system-reminder>\ngit\n</system-reminder>\n");
  356. expect(result.messages[2]?.content).toBe(
  357. "This session is being continued from a previous conversation.",
  358. );
  359. });
  360. it("adds no newline when the protocol does not merge adjacent user content", () => {
  361. const summary: RuntimeMessageEntry = {
  362. message: user("This session is being continued from a previous conversation."),
  363. metadata: { source: "legacy_synthetic", compactBoundary: { boundaryId: "b1" } },
  364. };
  365. const entries = [
  366. attachment("session_context", "git"),
  367. summary,
  368. entry(user("turn two"), "real_user"),
  369. entry(user("[Request interrupted by user]"), "interrupt_marker"),
  370. entry(user("next prompt"), "real_user"),
  371. ] satisfies RuntimeMessageEntry[];
  372. const result = buildProviderRequestMessages({ entries, useMidConversationSystem: false });
  373. // OpenAI 兼容协议不合并 user:上一次请求的最后一块(例如 "turn two")保持原字节。
  374. expect(result.messages.map((message) => message.content)).toEqual([
  375. "<system-reminder>\ngit\n</system-reminder>",
  376. "This session is being continued from a previous conversation.",
  377. "turn two",
  378. "[Request interrupted by user]",
  379. "next prompt",
  380. ]);
  381. });
  382. it.each([true, false])(
  383. "keeps the interrupt marker as plain user text that attachments pass (MCS=%s)",
  384. (useMidConversationSystem) => {
  385. const entries = [
  386. entry(user("first prompt"), "real_user"),
  387. entry(assistant("partial")),
  388. entry(user("[Request interrupted by user]"), "interrupt_marker"),
  389. attachment("runtime_mode", "mode"),
  390. entry(user("next prompt"), "real_user"),
  391. ] satisfies RuntimeMessageEntry[];
  392. const result = buildProviderRequestMessages({ entries, useMidConversationSystem, ...FOLD });
  393. const texts = result.messages.map((message) => [message.role, providerText(message)]);
  394. // 标记不冒泡、不进 system;后面的输入前以换行结尾。
  395. expect(texts).toContainEqual(["user", "[Request interrupted by user]\n"]);
  396. const markerIndex = texts.findIndex(([, text]) => text.startsWith("[Request interrupted"));
  397. expect(texts[markerIndex - 1]?.[0]).toBe(useMidConversationSystem ? "assistant" : "user");
  398. expect(texts.at(-1)).toEqual(
  399. useMidConversationSystem
  400. ? ["system", expect.stringContaining("mode")]
  401. : ["user", "next prompt"],
  402. );
  403. },
  404. );
  405. it("projects non-context meta reminders to system without moving context prefix", () => {
  406. const entries = [
  407. entry(user("follow up"), "real_user"),
  408. attachment("runtime_mode", "mode"),
  409. attachment("todo_reminder", "todo"),
  410. attachment("output_style", "style"),
  411. ] satisfies RuntimeMessageEntry[];
  412. const result = buildProviderRequestMessages({ entries, applyCacheControl: true });
  413. expect(result.messages).toEqual([
  414. { role: "user", content: "follow up", cacheControl: { type: "ephemeral" } },
  415. { role: "system", content: "mode\n\ntodo\n\nstyle" },
  416. ]);
  417. expect(result.diagnostics.bubbledAttachmentEntryCount).toBe(3);
  418. expect(result.diagnostics.cacheControlIndex).toBe(0);
  419. expect(result.diagnostics.latestRealUserMessageIndex).toBe(0);
  420. });
  421. it("keeps the same real user anchor open for prefix and current-turn system projections", () => {
  422. const entries = [
  423. attachment("skills_listing", "skills"),
  424. entry(user("real prompt"), "real_user"),
  425. attachment("output_style", "style"),
  426. entry(assistant("assistant response")),
  427. ] satisfies RuntimeMessageEntry[];
  428. const result = buildProviderRequestMessages({ entries });
  429. expect(result.messages).toEqual([
  430. { role: "user", content: "real prompt" },
  431. { role: "system", content: "skills\n\nstyle" },
  432. { role: "assistant", content: "assistant response" },
  433. ]);
  434. });
  435. it("projects current-turn attachment reminders to system without crossing assistant boundaries", () => {
  436. const entries = [
  437. entry(assistant("previous response")),
  438. entry(user("follow-up prompt"), "real_user"),
  439. attachment("relevant_memory", "memory reminder"),
  440. attachment("runtime_mode", "runtime mode reminder"),
  441. entry(assistant("next response")),
  442. entry(user("later prompt"), "real_user"),
  443. ] satisfies RuntimeMessageEntry[];
  444. const result = buildProviderRequestMessages({ entries });
  445. expect(result.messages).toEqual([
  446. { role: "assistant", content: "previous response" },
  447. { role: "user", content: "follow-up prompt" },
  448. { role: "system", content: "memory reminder\n\nruntime mode reminder" },
  449. { role: "assistant", content: "next response" },
  450. { role: "user", content: "later prompt" },
  451. ]);
  452. expect(result.diagnostics.bubbledAttachmentEntryCount).toBe(2);
  453. });
  454. it("places cache-control on the latest non-system message after projection", () => {
  455. const entries = [
  456. entry(user("inspect the repo"), "real_user"),
  457. entry(assistant("used Read")),
  458. entry(toolResult("read result")),
  459. entry(user("output style reminder"), "output_style"),
  460. ] satisfies RuntimeMessageEntry[];
  461. const result = buildProviderRequestMessages({ entries, applyCacheControl: true });
  462. expect(result.messages).toEqual([
  463. { role: "user", content: "inspect the repo" },
  464. { role: "assistant", content: "used Read" },
  465. {
  466. role: "tool",
  467. content: "read result",
  468. toolCallId: "tool-1",
  469. toolName: "Read",
  470. },
  471. {
  472. role: "user",
  473. content: "output style reminder",
  474. cacheControl: { type: "ephemeral" },
  475. },
  476. ]);
  477. expect(result.diagnostics.cacheControlIndex).toBe(3);
  478. expect(result.diagnostics.latestRealUserMessageIndex).toBe(0);
  479. });
  480. it("keeps plugin reference after the user while placing cache-control on that user", () => {
  481. const entries = [
  482. entry(user("use the plugin"), "real_user"),
  483. attachment("plugin_reference", "<plugin_reference>demo</plugin_reference>"),
  484. ] satisfies RuntimeMessageEntry[];
  485. const result = buildProviderRequestMessages({ entries, applyCacheControl: true });
  486. expect(result.messages).toEqual([
  487. {
  488. role: "user",
  489. content: "use the plugin",
  490. cacheControl: { type: "ephemeral" },
  491. },
  492. {
  493. role: "system",
  494. content: "<plugin_reference>demo</plugin_reference>",
  495. },
  496. ]);
  497. expect(result.diagnostics.cacheControlIndex).toBe(0);
  498. expect(result.diagnostics.latestRealUserMessageIndex).toBe(0);
  499. });
  500. it("moves cache-control before the latest message when cache write is skipped", () => {
  501. const entries = [
  502. entry(user("inspect the repo"), "real_user"),
  503. entry(assistant("summarizable response")),
  504. entry(user("compact prompt")),
  505. ] satisfies RuntimeMessageEntry[];
  506. const result = buildProviderRequestMessages({
  507. entries,
  508. applyCacheControl: true,
  509. skipCacheWrite: true,
  510. });
  511. expect(result.messages).toEqual([
  512. { role: "user", content: "inspect the repo" },
  513. {
  514. role: "assistant",
  515. content: "summarizable response",
  516. cacheControl: { type: "ephemeral" },
  517. },
  518. { role: "user", content: "compact prompt" },
  519. ]);
  520. expect(result.diagnostics.cacheControlIndex).toBe(1);
  521. });
  522. it("places cache-control on a tool message when it is the latest non-system message", () => {
  523. const entries = [
  524. entry(user("inspect the repo"), "real_user"),
  525. entry(assistant("used Read")),
  526. entry(toolResult("read result")),
  527. ] satisfies RuntimeMessageEntry[];
  528. const result = buildProviderRequestMessages({ entries, applyCacheControl: true });
  529. expect(result.messages).toEqual([
  530. { role: "user", content: "inspect the repo" },
  531. { role: "assistant", content: "used Read" },
  532. {
  533. role: "tool",
  534. content: "read result",
  535. toolCallId: "tool-1",
  536. toolName: "Read",
  537. cacheControl: { type: "ephemeral" },
  538. },
  539. ]);
  540. expect(result.diagnostics.cacheControlIndex).toBe(2);
  541. });
  542. it("projects a todo reminder after a tool result as mid-conversation system", () => {
  543. const entries = [
  544. entry(user("inspect the repo"), "real_user"),
  545. entry(assistant("used Read")),
  546. entry(toolResult("read result")),
  547. attachment("todo_reminder", "todo body"),
  548. ] satisfies RuntimeMessageEntry[];
  549. const result = buildProviderRequestMessages({ entries, applyCacheControl: true });
  550. expect(result.messages).toEqual([
  551. { role: "user", content: "inspect the repo" },
  552. { role: "assistant", content: "used Read" },
  553. {
  554. role: "tool",
  555. content: "read result",
  556. toolCallId: "tool-1",
  557. toolName: "Read",
  558. cacheControl: { type: "ephemeral" },
  559. },
  560. { role: "system", content: "todo body" },
  561. ]);
  562. expect(result.diagnostics.cacheControlIndex).toBe(2);
  563. });
  564. it("delays a pending mid-conversation system reminder until sibling tool results complete", () => {
  565. const entries = [
  566. entry(user("inspect the repo"), "real_user"),
  567. entry(assistant("issued parallel tools")),
  568. entry(toolResult("read result", "tool-1", "Read")),
  569. attachment("todo_reminder", "todo body"),
  570. entry(toolResult("grep result", "tool-2", "Grep")),
  571. entry(toolResult("glob result", "tool-3", "Glob")),
  572. entry(assistant("next answer")),
  573. ] satisfies RuntimeMessageEntry[];
  574. const result = buildProviderRequestMessages({ entries });
  575. expect(result.messages).toEqual([
  576. { role: "user", content: "inspect the repo" },
  577. { role: "assistant", content: "issued parallel tools" },
  578. {
  579. role: "tool",
  580. content: "read result",
  581. toolCallId: "tool-1",
  582. toolName: "Read",
  583. },
  584. {
  585. role: "tool",
  586. content: "grep result",
  587. toolCallId: "tool-2",
  588. toolName: "Grep",
  589. },
  590. {
  591. role: "tool",
  592. content: "glob result",
  593. toolCallId: "tool-3",
  594. toolName: "Glob",
  595. },
  596. { role: "system", content: "todo body" },
  597. { role: "assistant", content: "next answer" },
  598. ]);
  599. });
  600. it("keeps legacy reminder text after sibling tool results when MCS is disabled", () => {
  601. const entries = [
  602. entry(user("inspect the repo"), "real_user"),
  603. entry(assistant("issued parallel tools")),
  604. entry(toolResult("read result", "tool-1", "Read")),
  605. attachment("todo_reminder", "todo body"),
  606. entry(toolResult("grep result", "tool-2", "Grep")),
  607. entry(toolResult("glob result", "tool-3", "Glob")),
  608. entry(assistant("next answer")),
  609. ] satisfies RuntimeMessageEntry[];
  610. const result = buildProviderRequestMessages({
  611. entries,
  612. useMidConversationSystem: false,
  613. });
  614. expect(result.messages).toEqual([
  615. { role: "user", content: "inspect the repo" },
  616. { role: "assistant", content: "issued parallel tools" },
  617. {
  618. role: "tool",
  619. content: "read result",
  620. toolCallId: "tool-1",
  621. toolName: "Read",
  622. },
  623. {
  624. role: "tool",
  625. content: "grep result",
  626. toolCallId: "tool-2",
  627. toolName: "Grep",
  628. },
  629. {
  630. role: "tool",
  631. content: "glob result",
  632. toolCallId: "tool-3",
  633. toolName: "Glob",
  634. },
  635. {
  636. role: "user",
  637. content: "<system-reminder>\ntodo body\n</system-reminder>",
  638. },
  639. { role: "assistant", content: "next answer" },
  640. ]);
  641. });
  642. it("trims a string tool result and its reminders when folding them", () => {
  643. const entries = [
  644. entry(assistant("used Bash")),
  645. entry(toolResult("bash output\n", "tool-1", "Bash")),
  646. attachment("todo_reminder", "todo body"),
  647. entry(user(" <system-reminder>\nmemory\n</system-reminder>\n"), "relevant_memory"),
  648. ] satisfies RuntimeMessageEntry[];
  649. const result = buildProviderRequestMessages({
  650. entries,
  651. useMidConversationSystem: false,
  652. ...FOLD,
  653. });
  654. expect(result.messages).toEqual([
  655. { role: "assistant", content: "used Bash" },
  656. {
  657. role: "tool",
  658. content:
  659. "bash output\n\n<system-reminder>\ntodo body\n</system-reminder>\n\n<system-reminder>\nmemory\n</system-reminder>",
  660. toolCallId: "tool-1",
  661. toolName: "Bash",
  662. },
  663. ]);
  664. });
  665. it("appends reminder text blocks to an array tool result without trimming", () => {
  666. const image = {
  667. type: "image" as const,
  668. mediaType: "image/png",
  669. dataUrl: "data:image/png;base64,abc",
  670. };
  671. const entries = [
  672. entry(assistant("read two files")),
  673. entry({
  674. role: "tool",
  675. content: [{ type: "text", text: "page" }],
  676. toolCallId: "tool-1",
  677. toolName: "Read",
  678. }),
  679. entry({ role: "tool", content: [image], toolCallId: "tool-2", toolName: "Read" }),
  680. attachment("todo_reminder", "todo body"),
  681. attachment("output_style", "style body"),
  682. ] satisfies RuntimeMessageEntry[];
  683. const result = buildProviderRequestMessages({
  684. entries,
  685. useMidConversationSystem: false,
  686. ...FOLD,
  687. });
  688. expect(result.messages.slice(1)).toEqual([
  689. {
  690. role: "tool",
  691. content: [{ type: "text", text: "page" }],
  692. toolCallId: "tool-1",
  693. toolName: "Read",
  694. },
  695. {
  696. role: "tool",
  697. content: [
  698. image,
  699. { type: "text", text: "<system-reminder>\ntodo body\n</system-reminder>\n" },
  700. { type: "text", text: "<system-reminder>\nstyle body\n</system-reminder>" },
  701. ],
  702. toolCallId: "tool-2",
  703. toolName: "Read",
  704. },
  705. ]);
  706. });
  707. it("does not fold reminders into a tool result that holds tool references", () => {
  708. const entries = [
  709. entry(assistant("searched tools")),
  710. entry({
  711. role: "tool",
  712. content: [{ type: "tool_reference", toolName: "Write" }],
  713. toolCallId: "tool-1",
  714. toolName: "ToolSearch",
  715. }),
  716. attachment("todo_reminder", "todo body"),
  717. ] satisfies RuntimeMessageEntry[];
  718. const result = buildProviderRequestMessages({
  719. entries,
  720. useMidConversationSystem: false,
  721. ...FOLD,
  722. });
  723. expect(result.messages.slice(1)).toEqual([
  724. {
  725. role: "tool",
  726. content: [{ type: "tool_reference", toolName: "Write" }],
  727. toolCallId: "tool-1",
  728. toolName: "ToolSearch",
  729. },
  730. { role: "user", content: "<system-reminder>\ntodo body\n</system-reminder>" },
  731. ]);
  732. });
  733. it("folds mid-turn inputs with the other reminders but never folds user inputs", () => {
  734. const steer: RuntimeMessageEntry = {
  735. message: user("check the tests too"),
  736. metadata: { source: "real_user", inputPresentation: "user_steer" },
  737. };
  738. const entries = [
  739. entry(user("inspect"), "real_user"),
  740. entry(assistant("used Read")),
  741. entry(toolResult("read result")),
  742. attachment("todo_reminder", "todo body"),
  743. steer,
  744. attachment("output_style", "style body"),
  745. entry(assistant("used Grep")),
  746. entry(toolResult("grep result", "tool-2", "Grep")),
  747. entry(user("next prompt"), "real_user"),
  748. ] satisfies RuntimeMessageEntry[];
  749. const result = buildProviderRequestMessages({
  750. entries,
  751. useMidConversationSystem: false,
  752. ...FOLD,
  753. });
  754. const folded = providerText(result.messages[2]!);
  755. expect(
  756. folded.startsWith("read result\n\n<system-reminder>\ntodo body\n</system-reminder>\n\n"),
  757. ).toBe(true);
  758. expect(folded).toContain("check the tests too");
  759. expect(folded.endsWith("\n\n<system-reminder>\nstyle body\n</system-reminder>")).toBe(true);
  760. expect(result.messages.slice(3)).toEqual([
  761. { role: "assistant", content: "used Grep" },
  762. { role: "tool", content: "grep result", toolCallId: "tool-2", toolName: "Grep" },
  763. { role: "user", content: "next prompt" },
  764. ]);
  765. expect(result.diagnostics.latestRealUserMessageIndex).toBe(5);
  766. expect(result.sourceEntries[2]).toBe(entries[2]);
  767. expect(result.sourceEntries[5]).toBe(entries[8]);
  768. });
  769. describe("native ToolSearch Tool loaded notice", () => {
  770. const searchBatch = [
  771. entry(assistant("searched tools")),
  772. entry({
  773. role: "tool",
  774. content: [{ type: "tool_reference", toolName: "Write" }],
  775. toolCallId: "search-1",
  776. toolName: "ToolSearch",
  777. }),
  778. entry(toolResult("out", "bash-1", "Bash")),
  779. ] satisfies RuntimeMessageEntry[];
  780. const loaded = { loadedToolCallIds: new Set(["search-1"]) };
  781. it("keeps reminders after Tool loaded instead of folding them into the batch", () => {
  782. const result = buildProviderRequestMessages({
  783. entries: [...searchBatch, attachment("session_context", "ctx")],
  784. ...loaded,
  785. ...FOLD,
  786. });
  787. // Tool loaded. 在并入之前插入:提醒跟在它后面,Bash 结果保持原样。
  788. expect(result.messages.slice(1)).toEqual([
  789. {
  790. role: "tool",
  791. content: [{ type: "tool_reference", toolName: "Write" }],
  792. toolCallId: "search-1",
  793. toolName: "ToolSearch",
  794. },
  795. toolResult("out", "bash-1", "Bash"),
  796. { role: "user", content: "Tool loaded." },
  797. { role: "user", content: "<system-reminder>\nctx\n</system-reminder>" },
  798. ]);
  799. });
  800. it("ends Tool loaded with a newline before a following user input", () => {
  801. const prompt = entry(user("check the tests too"), "real_user");
  802. const result = buildProviderRequestMessages({
  803. entries: [...searchBatch, prompt],
  804. ...loaded,
  805. ...FOLD,
  806. });
  807. expect(result.messages[3]).toEqual({ role: "user", content: "Tool loaded.\n" });
  808. expect(providerText(result.messages[4]!)).toContain("check the tests too");
  809. });
  810. });
  811. describe("MCS human steer in the run's system message", () => {
  812. const steer = (content: ModelInputMessage["content"]): RuntimeMessageEntry => ({
  813. message: user(content),
  814. metadata: { source: "real_user", inputPresentation: "user_steer" },
  815. });
  816. const steerText = (body: string) =>
  817. `The user sent a new message while you were working:\n${body}\n\nThis is how ZCode surfaces messages the user sends mid-turn — within the running turn, often alongside the next tool result, rather than as a separate conversation turn. Address the message above as you continue this turn.`;
  818. // guide 是轮内中途消息:MCS 下与其他中途消息一样并入 run 的 system,不带外层标签。
  819. it("puts a text steer into the run system message, user-side reminders still fold", () => {
  820. const entries = [
  821. entry(assistant("used Read")),
  822. entry(toolResult("read result")),
  823. steer("check the tests too"),
  824. attachment("session_context", "git"),
  825. attachment("todo_reminder", "todo body"),
  826. ] satisfies RuntimeMessageEntry[];
  827. const result = buildProviderRequestMessages({ entries, ...FOLD });
  828. expect(result.messages).toEqual([
  829. assistant("used Read"),
  830. toolResult("read result\n\n<system-reminder>\ngit\n</system-reminder>"),
  831. { role: "system", content: `${steerText("check the tests too")}\n\ntodo body` },
  832. ]);
  833. });
  834. it("keeps several steers in order in one system message before the next assistant", () => {
  835. const entries = [
  836. entry(assistant("used Read")),
  837. entry(toolResult("read result")),
  838. steer("first"),
  839. attachment("session_context", "git"),
  840. steer("second"),
  841. entry(assistant("next")),
  842. ] satisfies RuntimeMessageEntry[];
  843. const result = buildProviderRequestMessages({ entries, ...FOLD });
  844. expect(result.messages).toEqual([
  845. assistant("used Read"),
  846. toolResult("read result\n\n<system-reminder>\ngit\n</system-reminder>"),
  847. { role: "system", content: `${steerText("first")}\n\n${steerText("second")}` },
  848. assistant("next"),
  849. ]);
  850. });
  851. // text-only 回复之后没有 user/tool 锚点,system 放不下,整组降级为一条 user reminder。
  852. it("degrades a steer after a text-only reply to one wrapped user reminder", () => {
  853. const entries = [
  854. entry(user("first"), "real_user"),
  855. entry(assistant("answer")),
  856. steer("follow up"),
  857. ] satisfies RuntimeMessageEntry[];
  858. const result = buildProviderRequestMessages({ entries, ...FOLD });
  859. expect(result.messages).toEqual([
  860. user("first"),
  861. assistant("answer"),
  862. user(`<system-reminder>\n${steerText("follow up")}\n</system-reminder>`),
  863. ]);
  864. });
  865. // 带图 guide 放不进 system:MCS 开关下都留在 user 侧,文本包装一次放首块,不并入 tool result。
  866. it.each([true, false])("keeps a steer with media on the user side (MCS=%s)", (mcs) => {
  867. const image = {
  868. type: "image" as const,
  869. mediaType: "image/png",
  870. dataUrl: "data:image/png;base64,abc",
  871. };
  872. const entries = [
  873. entry(assistant("used Read")),
  874. entry(toolResult("read result")),
  875. steer([{ type: "text", text: "look at this" }, image]),
  876. ] satisfies RuntimeMessageEntry[];
  877. const result = buildProviderRequestMessages({
  878. entries,
  879. useMidConversationSystem: mcs,
  880. ...FOLD,
  881. });
  882. expect(result.messages).toEqual([
  883. assistant("used Read"),
  884. toolResult("read result"),
  885. user([
  886. {
  887. type: "text",
  888. text: `<system-reminder>\n${steerText("look at this")}\n</system-reminder>`,
  889. },
  890. image,
  891. ]),
  892. ]);
  893. });
  894. });
  895. describe("send-now before the preempted prompt has any output", () => {
  896. // 历史:B 还没有任何输出就被 send-now 抢占(不写中断标记),C 开新一轮。
  897. // 现在 C 是普通用户消息;旧版本把 C 存成 user_steer,已存会话照旧投影。
  898. const entriesWith = (c: RuntimeMessageEntry) =>
  899. [
  900. entry(user("first"), "real_user"),
  901. entry(assistant("answer A")),
  902. entry(user("prompt B"), "real_user"),
  903. attachment("output_style", "style for B"),
  904. c,
  905. attachment("todo_reminder", "todo after C"),
  906. ] satisfies RuntimeMessageEntry[];
  907. const plainC = entry(user("message C"), "real_user");
  908. const storedSteerC: RuntimeMessageEntry = {
  909. message: user("message C"),
  910. metadata: { source: "real_user", inputPresentation: "user_steer" },
  911. };
  912. const order = (messages: ModelInputMessage[], ...needles: string[]): number[] =>
  913. needles.map((needle) =>
  914. messages.findIndex((message) => providerText(message).includes(needle)),
  915. );
  916. // 人类输入按时间顺序:被抢占的 B 在前,新消息 C 在后。
  917. // MCS 关:公告照常越过普通 user;普通 C 之后的提醒越过 C 和 B,旧 user_steer C 之后的提醒留在 C 之后。
  918. // MCS 开:run 内的 MCS 文本合成一条 system,放在 run 末尾(C 之后)。
  919. it.each([
  920. ["plain C, MCS off", plainC, false, ["style for B", "todo after C", "prompt B", "message C"]],
  921. ["plain C, MCS on", plainC, true, ["prompt B", "message C", "style for B"]],
  922. [
  923. "stored user_steer C, MCS off",
  924. storedSteerC,
  925. false,
  926. ["style for B", "prompt B", "message C", "todo after C"],
  927. ],
  928. ])("keeps the new message after the preempted prompt (%s)", (_label, c, mcs, expected) => {
  929. const result = buildProviderRequestMessages({
  930. entries: entriesWith(c),
  931. useMidConversationSystem: mcs,
  932. });
  933. const indices = order(result.messages, ...expected);
  934. expect(indices[0]).toBeGreaterThan(1);
  935. expect(indices).toEqual([...new Set(indices)].sort((a, b) => a - b));
  936. });
  937. // MCS 开时旧 user_steer C 是中途消息,和 run 内的提醒按生成顺序合成 B 之后的一条 system。
  938. it("keeps a stored user_steer C after the preempted prompt in the run system (MCS on)", () => {
  939. const result = buildProviderRequestMessages({
  940. entries: entriesWith(storedSteerC),
  941. useMidConversationSystem: true,
  942. });
  943. expect(result.messages.slice(2).map((message) => message.role)).toEqual(["user", "system"]);
  944. expect(providerText(result.messages[2]!)).toBe("prompt B");
  945. const system = providerText(result.messages[3]!);
  946. expect(order([user(system)], "style for B", "message C", "todo after C")).toEqual([0, 0, 0]);
  947. expect(system.indexOf("style for B")).toBeLessThan(system.indexOf("message C"));
  948. expect(system.indexOf("message C")).toBeLessThan(system.indexOf("todo after C"));
  949. });
  950. });
  951. // 被打断时只产出了思考(send now、停止、思考后流失败)或只有空白文字的回复。Anthropic 协议的请求不带它,
  952. // 删除是投影的第一步:system 按「后面是 assistant」落在它前面,它再被删掉,system 就直接接 user,
  953. // provider 返回 400,之后整个会话的请求都失败。
  954. describe("assistant replies the protocol drops", () => {
  955. const DROP = { dropReasoningOnlyOrBlankAssistants: true } as const;
  956. const reasoningOnly: ModelInputMessage = {
  957. role: "assistant",
  958. content: [{ type: "reasoning", text: "thinking B" }],
  959. };
  960. const preempted = (reply: ModelInputMessage, ...rest: RuntimeMessageEntry[]) =>
  961. [
  962. entry(user("first"), "real_user"),
  963. entry(assistant("answer A")),
  964. entry(user("prompt B"), "real_user"),
  965. attachment("environment", "env for B"),
  966. entry(reply),
  967. entry(user("message C"), "real_user"),
  968. ...rest,
  969. ] satisfies RuntimeMessageEntry[];
  970. const roles = (messages: ModelInputMessage[]) => messages.map((message) => message.role);
  971. it.each([
  972. ["reasoning-only", reasoningOnly],
  973. ["blank", { role: "assistant", content: [{ type: "text", text: "\n\n" }] }],
  974. ["placeholder", { role: "assistant", content: [{ type: "text", text: "(no content)" }] }],
  975. [
  976. "reasoning and blank",
  977. {
  978. role: "assistant",
  979. content: [
  980. { type: "text", text: "\n\n" },
  981. { type: "reasoning", text: "thinking B" },
  982. ],
  983. },
  984. ],
  985. ] satisfies [string, ModelInputMessage][])(
  986. "puts the run's system after the new input when a %s reply is dropped",
  987. (_label, reply) => {
  988. const result = buildProviderRequestMessages({
  989. entries: preempted(reply),
  990. useMidConversationSystem: true,
  991. ...FOLD,
  992. ...DROP,
  993. });
  994. expect(roles(result.messages)).toEqual(["user", "assistant", "user", "user", "system"]);
  995. expect(providerText(result.messages[2]!)).toBe("prompt B\n");
  996. expect(providerText(result.messages[3]!)).toBe("message C");
  997. expect(providerText(result.messages[4]!)).toContain("env for B");
  998. },
  999. );
  1000. // MCS 关:被删的回复不再是冒泡停止点,C 之后的提醒越过 C 和 B,落在 A 之后。
  1001. it("bubbles the new turn's reminders past the earlier prompt when MCS is off", () => {
  1002. const result = buildProviderRequestMessages({
  1003. entries: preempted(reasoningOnly, attachment("output_style", "style after C")),
  1004. useMidConversationSystem: false,
  1005. ...FOLD,
  1006. ...DROP,
  1007. });
  1008. const texts = result.messages.map(providerText);
  1009. const indexOf = (needle: string) => texts.findIndex((text) => text.includes(needle));
  1010. expect(roles(result.messages).filter((role) => role === "assistant")).toHaveLength(1);
  1011. expect(JSON.stringify(result.messages)).not.toContain("thinking B");
  1012. expect(indexOf("answer A")).toBeLessThan(indexOf("style after C"));
  1013. expect(indexOf("style after C")).toBeLessThan(indexOf("prompt B"));
  1014. expect(texts[indexOf("prompt B")]).toBe("prompt B\n");
  1015. expect(texts.at(-1)).toBe("message C");
  1016. });
  1017. // 思考用完输出上限:回复只有思考,runtime 追加 Continue 提示;回复删除后提示直接接在 B 后面。
  1018. it("separates the earlier prompt from a Continue prompt after the reply is dropped", () => {
  1019. const result = buildProviderRequestMessages({
  1020. entries: [
  1021. ...preempted(reasoningOnly).slice(0, 4),
  1022. entry(reasoningOnly),
  1023. entry(user("Output token limit hit."), "output_token_continuation"),
  1024. ],
  1025. useMidConversationSystem: false,
  1026. ...FOLD,
  1027. ...DROP,
  1028. });
  1029. expect(result.messages.slice(-2).map(providerText)).toEqual([
  1030. "prompt B\n",
  1031. "Output token limit hit.",
  1032. ]);
  1033. });
  1034. // 续写提示写入历史之前存的会话里,两段回复相邻。按条目判断:只删只有思考的第一段。
  1035. // 产出第二段的请求里第一段已被删除,整段保留会把第一段的思考放回第二段前面。
  1036. it("drops only the reasoning-only entry of two adjacent assistant entries", () => {
  1037. const result = buildProviderRequestMessages({
  1038. entries: [
  1039. ...preempted(reasoningOnly).slice(0, 4),
  1040. entry(reasoningOnly),
  1041. entry({
  1042. role: "assistant",
  1043. content: [
  1044. { type: "reasoning", text: "thinking C" },
  1045. { type: "text", text: "answer C" },
  1046. ],
  1047. }),
  1048. entry(user("message D"), "real_user"),
  1049. ],
  1050. useMidConversationSystem: false,
  1051. ...FOLD,
  1052. ...DROP,
  1053. });
  1054. const assistants = result.messages.filter((message) => message.role === "assistant");
  1055. expect(assistants).toHaveLength(2);
  1056. expect(JSON.stringify(assistants[1])).toContain("thinking C");
  1057. expect(JSON.stringify(result.messages)).not.toContain("thinking B");
  1058. });
  1059. // send now 最常见的形态:工具结果之后、模型还在思考时打断。被删回复前面是 tool result,
  1060. // 提醒按 MCS 落点或并入 tool result,都不能让 system 直接接 user。
  1061. it.each([true, false])(
  1062. "keeps a valid request when a reply after a tool result is dropped (MCS %s)",
  1063. (useMidConversationSystem) => {
  1064. const result = buildProviderRequestMessages({
  1065. entries: [
  1066. entry(user("inspect"), "real_user"),
  1067. entry({
  1068. role: "assistant",
  1069. content: "used Read",
  1070. toolCalls: [{ id: "tool-1", name: "Read", input: {} }],
  1071. }),
  1072. entry(toolResult("read result")),
  1073. attachment("environment", "env after tool"),
  1074. entry(reasoningOnly),
  1075. entry(user("message C"), "real_user"),
  1076. ],
  1077. useMidConversationSystem,
  1078. ...FOLD,
  1079. ...DROP,
  1080. });
  1081. const messages = result.messages;
  1082. messages.forEach((message, index) => {
  1083. if (message.role === "system")
  1084. expect(messages[index + 1]?.role ?? "assistant").toBe("assistant");
  1085. });
  1086. expect(JSON.stringify(messages)).not.toContain("thinking B");
  1087. expect(messages.some((message) => message.role === "tool")).toBe(true);
  1088. expect(JSON.stringify(messages)).toContain("env after tool");
  1089. expect(messages.map(providerText).join("")).toContain("message C");
  1090. },
  1091. );
  1092. it.each([
  1093. [
  1094. "a tool call",
  1095. {
  1096. role: "assistant",
  1097. content: [{ type: "reasoning", text: "thinking B" }],
  1098. toolCalls: [{ id: "call-1", name: "Read", input: {} }],
  1099. },
  1100. ],
  1101. ["visible text", { role: "assistant", content: [{ type: "text", text: "partial" }] }],
  1102. ["legacy string content", { role: "assistant", content: " " }],
  1103. // 留作估算锚点的空回复存成空字符串(上一条);空数组的 every 恒为真,要单独排除。
  1104. ["empty content", { role: "assistant", content: [] }],
  1105. ] satisfies [string, ModelInputMessage][])("keeps a reply with %s", (_label, reply) => {
  1106. const result = buildProviderRequestMessages({
  1107. entries: preempted(reply),
  1108. useMidConversationSystem: false,
  1109. ...DROP,
  1110. });
  1111. expect(roles(result.messages).filter((role) => role === "assistant")).toHaveLength(2);
  1112. });
  1113. it.each([true, false])("reads the drop switch from the model capability (%s)", (drop) => {
  1114. const model = {
  1115. ...createTestRuntimeModel({
  1116. generateText: async () => ({ text: "" }) as never,
  1117. propertyOverrides: { supportsMidConversationSystem: true },
  1118. }),
  1119. requestCapabilities: { dropReasoningOnlyOrBlankAssistants: drop },
  1120. };
  1121. const result = buildRuntimeProviderRequestMessages(
  1122. { config: {} },
  1123. { model, entries: preempted(reasoningOnly) },
  1124. );
  1125. expect(roles(result.messages)).toEqual(
  1126. drop
  1127. ? ["user", "assistant", "user", "user", "system"]
  1128. : ["user", "assistant", "user", "system", "assistant", "user"],
  1129. );
  1130. });
  1131. });
  1132. it("does not keep a folded steer as the latest real user for the media budget", () => {
  1133. const entries = [
  1134. entry(user("inspect"), "real_user"),
  1135. entry(assistant("used Read")),
  1136. entry(toolResult("read result")),
  1137. {
  1138. message: user("check the tests too"),
  1139. metadata: { source: "real_user", inputPresentation: "user_steer" },
  1140. },
  1141. ] satisfies RuntimeMessageEntry[];
  1142. const result = buildProviderRequestMessages({
  1143. entries,
  1144. useMidConversationSystem: false,
  1145. ...FOLD,
  1146. });
  1147. expect(result.messages).toHaveLength(3);
  1148. expect(result.diagnostics.latestRealUserMessageIndex).toBe(-1);
  1149. });
  1150. it.each([true, false])("reads the fold switch from the model capability (%s)", (fold) => {
  1151. const model = {
  1152. ...createTestRuntimeModel({
  1153. generateText: async () => ({ text: "" }) as never,
  1154. propertyOverrides: { supportsMidConversationSystem: false },
  1155. }),
  1156. requestCapabilities: { foldRemindersIntoToolResults: fold },
  1157. };
  1158. const result = buildRuntimeProviderRequestMessages(
  1159. { config: {} },
  1160. {
  1161. model,
  1162. entries: [
  1163. entry(assistant("used Read")),
  1164. entry(toolResult("read result")),
  1165. attachment("todo_reminder", "todo body"),
  1166. ],
  1167. },
  1168. );
  1169. expect(result.messages.map((message) => message.role)).toEqual(
  1170. fold ? ["assistant", "tool"] : ["assistant", "tool", "user"],
  1171. );
  1172. });
  1173. it("keeps a todo reminder anchored after its tool result when later tool exchanges are appended", () => {
  1174. const entries = [
  1175. entry(user("inspect the repo"), "real_user"),
  1176. entry(assistant("used Read")),
  1177. entry(toolResult("read result")),
  1178. attachment("todo_reminder", "todo body"),
  1179. entry(assistant("used Grep")),
  1180. {
  1181. message: {
  1182. role: "tool",
  1183. content: "grep result",
  1184. toolCallId: "tool-2",
  1185. toolName: "Grep",
  1186. },
  1187. },
  1188. ] satisfies RuntimeMessageEntry[];
  1189. const result = buildProviderRequestMessages({ entries, applyCacheControl: true });
  1190. expect(result.messages).toEqual([
  1191. { role: "user", content: "inspect the repo" },
  1192. { role: "assistant", content: "used Read" },
  1193. {
  1194. role: "tool",
  1195. content: "read result",
  1196. toolCallId: "tool-1",
  1197. toolName: "Read",
  1198. },
  1199. { role: "system", content: "todo body" },
  1200. { role: "assistant", content: "used Grep" },
  1201. {
  1202. role: "tool",
  1203. content: "grep result",
  1204. toolCallId: "tool-2",
  1205. toolName: "Grep",
  1206. cacheControl: { type: "ephemeral" },
  1207. },
  1208. ]);
  1209. });
  1210. it("projects a todo reminder after an Anthropic-style tool-result user message", () => {
  1211. const entries = [
  1212. entry(user("inspect the repo"), "real_user"),
  1213. entry(assistant("used Read")),
  1214. entry(toolResultUser("read result")),
  1215. attachment("todo_reminder", "todo body"),
  1216. ] satisfies RuntimeMessageEntry[];
  1217. const result = buildProviderRequestMessages({ entries, applyCacheControl: true });
  1218. expect(result.messages).toEqual([
  1219. { role: "user", content: "inspect the repo" },
  1220. { role: "assistant", content: "used Read" },
  1221. {
  1222. role: "user",
  1223. content: [{ type: "text", text: "read result" }],
  1224. toolCallId: "tool-1",
  1225. toolName: "Read",
  1226. cacheControl: { type: "ephemeral" },
  1227. },
  1228. { role: "system", content: "todo body" },
  1229. ]);
  1230. });
  1231. it("keeps a pending mid-conversation system reminder after a following user message", () => {
  1232. const entries = [
  1233. entry(user("first prompt"), "real_user"),
  1234. attachment("output_style", "style body"),
  1235. entry(user("second prompt"), "target_continuation"),
  1236. ] satisfies RuntimeMessageEntry[];
  1237. const result = buildProviderRequestMessages({ entries });
  1238. expect(result.messages).toEqual([
  1239. { role: "user", content: "first prompt" },
  1240. { role: "user", content: "second prompt" },
  1241. { role: "system", content: "style body" },
  1242. ]);
  1243. });
  1244. it("does not treat a mid-conversation system fallback as latest real user", () => {
  1245. const entries = [
  1246. entry(assistant("used Read")),
  1247. entry(toolResult("read result")),
  1248. attachment("output_style", "style body"),
  1249. entry({ role: "system", content: "stable system" }),
  1250. ] satisfies RuntimeMessageEntry[];
  1251. const result = buildProviderRequestMessages({ entries, applyCacheControl: true });
  1252. expect(result.messages).toEqual([
  1253. { role: "assistant", content: "used Read" },
  1254. {
  1255. role: "tool",
  1256. content: "read result",
  1257. toolCallId: "tool-1",
  1258. toolName: "Read",
  1259. },
  1260. {
  1261. role: "user",
  1262. content: "<system-reminder>\nstyle body\n</system-reminder>",
  1263. cacheControl: { type: "ephemeral" },
  1264. },
  1265. { role: "system", content: "stable system" },
  1266. ]);
  1267. expect(result.diagnostics.latestRealUserMessageIndex).toBeUndefined();
  1268. });
  1269. it("places cache-control on an assistant message when it is the latest non-system message", () => {
  1270. const entries = [
  1271. entry(user("first prompt"), "real_user"),
  1272. entry(assistant("assistant answer")),
  1273. ] satisfies RuntimeMessageEntry[];
  1274. const result = buildProviderRequestMessages({ entries, applyCacheControl: true });
  1275. expect(result.messages).toEqual([
  1276. { role: "user", content: "first prompt" },
  1277. {
  1278. role: "assistant",
  1279. content: "assistant answer",
  1280. cacheControl: { type: "ephemeral" },
  1281. },
  1282. ]);
  1283. expect(result.diagnostics.cacheControlIndex).toBe(1);
  1284. });
  1285. it("preserves system cache-control and clears stale non-system cache-control", () => {
  1286. const entries = [
  1287. {
  1288. message: {
  1289. role: "system",
  1290. content: "stable system",
  1291. cacheControl: { type: "ephemeral" },
  1292. },
  1293. },
  1294. entry({ ...user("first prompt"), cacheControl: { type: "ephemeral" } }, "real_user"),
  1295. entry({ ...assistant("assistant answer"), cacheControl: { type: "ephemeral" } }),
  1296. entry(toolResult("read result")),
  1297. ] satisfies RuntimeMessageEntry[];
  1298. const result = buildProviderRequestMessages({ entries, applyCacheControl: true });
  1299. expect(result.messages).toEqual([
  1300. {
  1301. role: "system",
  1302. content: "stable system",
  1303. cacheControl: { type: "ephemeral" },
  1304. },
  1305. { role: "user", content: "first prompt" },
  1306. { role: "assistant", content: "assistant answer" },
  1307. {
  1308. role: "tool",
  1309. content: "read result",
  1310. toolCallId: "tool-1",
  1311. toolName: "Read",
  1312. cacheControl: { type: "ephemeral" },
  1313. },
  1314. ]);
  1315. expect(result.diagnostics.cacheControlIndex).toBe(3);
  1316. });
  1317. it("does not bubble attachment-like reminders across tool-result user boundaries", () => {
  1318. const entries = [
  1319. entry(assistant("assistant used a tool")),
  1320. entry(toolResultUser()),
  1321. entry(user("memory reminder"), "relevant_memory"),
  1322. entry(user("next real prompt"), "real_user"),
  1323. ] satisfies RuntimeMessageEntry[];
  1324. const result = buildProviderRequestMessages({ entries });
  1325. expect(result.messages).toEqual([
  1326. { role: "assistant", content: "assistant used a tool" },
  1327. {
  1328. role: "user",
  1329. content: [{ type: "text", text: "tool result" }],
  1330. toolCallId: "tool-1",
  1331. toolName: "Read",
  1332. },
  1333. { role: "user", content: "memory reminder" },
  1334. { role: "user", content: "next real prompt" },
  1335. ]);
  1336. });
  1337. it("treats literal system-reminder user text as real input when metadata says real_user", () => {
  1338. const entries = [
  1339. entry(user("<system-reminder>\nthis is user-provided text\n</system-reminder>"), "real_user"),
  1340. entry(user("mode reminder"), "runtime_mode"),
  1341. ] satisfies RuntimeMessageEntry[];
  1342. const result = buildProviderRequestMessages({ entries });
  1343. expect(result.messages).toEqual([
  1344. {
  1345. role: "user",
  1346. content: "<system-reminder>\nthis is user-provided text\n</system-reminder>",
  1347. },
  1348. { role: "user", content: "mode reminder" },
  1349. ]);
  1350. });
  1351. it("keeps direct pasted image blocks in their original real-user content order", () => {
  1352. const entries = [
  1353. entry(
  1354. user([
  1355. { type: "text", text: "Please inspect this screenshot." },
  1356. { type: "image", mediaType: "image/png", dataUrl: "data:image/png;base64,paste" },
  1357. ]),
  1358. "real_user",
  1359. ),
  1360. entry(user("output style reminder"), "output_style"),
  1361. ] satisfies RuntimeMessageEntry[];
  1362. const result = buildProviderRequestMessages({ entries });
  1363. expect(result.messages).toEqual([
  1364. {
  1365. role: "user",
  1366. content: [
  1367. { type: "text", text: "Please inspect this screenshot." },
  1368. { type: "image", mediaType: "image/png", dataUrl: "data:image/png;base64,paste" },
  1369. ],
  1370. },
  1371. { role: "user", content: "output style reminder" },
  1372. ]);
  1373. });
  1374. it("is deterministic, idempotent, and does not mutate frozen runtime entries", () => {
  1375. const entries = deepFreeze([
  1376. {
  1377. message: {
  1378. role: "user",
  1379. content: [
  1380. { type: "image", mediaType: "image/png", dataUrl: "data:image/png;base64,abc" },
  1381. { type: "text", text: "image context" },
  1382. ],
  1383. },
  1384. metadata: systemReminderRuntimeMetadata("prompt_attachment"),
  1385. },
  1386. {
  1387. message: {
  1388. role: "user",
  1389. content: "real prompt",
  1390. cacheControl: { type: "ephemeral" },
  1391. },
  1392. metadata: realUserRuntimeMetadata(),
  1393. },
  1394. ] satisfies RuntimeMessageEntry[]);
  1395. const first = buildProviderRequestMessages({ entries, applyCacheControl: true, ...FOLD });
  1396. const second = buildProviderRequestMessages({ entries, applyCacheControl: true, ...FOLD });
  1397. const projectedAgain = buildProviderRequestMessages({
  1398. entries: first.messages.map((message) => ({ message })),
  1399. applyCacheControl: true,
  1400. ...FOLD,
  1401. });
  1402. expect(first).toEqual(second);
  1403. expect(projectedAgain.messages).toEqual(first.messages);
  1404. expect(first.messages).toEqual([
  1405. {
  1406. role: "user",
  1407. content: [
  1408. { type: "image", mediaType: "image/png", dataUrl: "data:image/png;base64,abc" },
  1409. { type: "text", text: "image context\n" },
  1410. ],
  1411. },
  1412. {
  1413. role: "user",
  1414. content: "real prompt",
  1415. cacheControl: { type: "ephemeral" },
  1416. },
  1417. ]);
  1418. });
  1419. it("returns request messages detached from runtime message objects", () => {
  1420. const inputMessage: ModelInputMessage = {
  1421. role: "assistant",
  1422. content: [{ type: "text", text: "original answer" }],
  1423. cacheControl: { type: "ephemeral" },
  1424. toolCalls: [{ id: "tool-1", name: "Read", input: { file_path: "notes.md" } }],
  1425. };
  1426. const entries = [{ message: inputMessage }] satisfies RuntimeMessageEntry[];
  1427. const projectedMessage = buildProviderRequestMessages({ entries }).messages[0]!;
  1428. expect(projectedMessage).not.toBe(inputMessage);
  1429. expect(projectedMessage.content).not.toBe(inputMessage.content);
  1430. expect(projectedMessage.cacheControl).not.toBe(inputMessage.cacheControl);
  1431. expect(projectedMessage.toolCalls).not.toBe(inputMessage.toolCalls);
  1432. if (typeof projectedMessage.content !== "string") {
  1433. const textBlock = projectedMessage.content[0];
  1434. if (textBlock?.type === "text") textBlock.text = "mutated answer";
  1435. }
  1436. projectedMessage.toolCalls![0]!.name = "Write";
  1437. projectedMessage.cacheControl = undefined;
  1438. expect(inputMessage).toEqual({
  1439. role: "assistant",
  1440. content: [{ type: "text", text: "original answer" }],
  1441. cacheControl: { type: "ephemeral" },
  1442. toolCalls: [{ id: "tool-1", name: "Read", input: { file_path: "notes.md" } }],
  1443. });
  1444. });
  1445. });
  1446. describe("compaction file restore projection", () => {
  1447. const called = 'Called the Read tool with the following input: {"file_path":"/w/a.txt"}';
  1448. const result = "Result of calling the Read tool:\n1\tA";
  1449. const note =
  1450. "Note: /w/big.txt was read before the last conversation was summarized, but the contents are too large to include. Use Read tool if you need to access it.";
  1451. const wrap = (body: string) => `<system-reminder>\n${body}\n</system-reminder>`;
  1452. const retainedToolRun = (): RuntimeMessageEntry[] => [
  1453. entry(user("prompt"), "real_user"),
  1454. entry({
  1455. role: "assistant",
  1456. content: "",
  1457. toolCalls: [{ id: "tool-1", name: "Read", input: { file_path: "/w/b.txt" } }],
  1458. }),
  1459. entry(toolResult("1\tB")),
  1460. ];
  1461. const compactionAttachments = (): RuntimeMessageEntry[] => [
  1462. attachment("resume_referenced_session_context", called),
  1463. attachment("resume_referenced_session_context", result),
  1464. attachment("compact_file_reference", note),
  1465. attachment("environment", "env body"),
  1466. ];
  1467. // 保留段以 tool result 结尾时,补回正文是 tool result 之后的独立 user 文本,不并入 tool result;
  1468. // 两条正文相邻时调用说明以换行结尾。引用提示和其余附件按 MCS 规则投影。
  1469. it("keeps restored bodies as separate user text after a retained tool result with MCS", () => {
  1470. const messages = buildProviderRequestMessages({
  1471. entries: [...retainedToolRun(), ...compactionAttachments()],
  1472. ...FOLD,
  1473. }).messages;
  1474. expect(messages.slice(2)).toEqual([
  1475. toolResult("1\tB"),
  1476. user(`${wrap(called)}\n`),
  1477. user(wrap(result)),
  1478. { role: "system", content: `${note}\n\nenv body` },
  1479. ]);
  1480. });
  1481. it("keeps restored bodies unfolded without MCS and stops the fold there", () => {
  1482. const messages = buildProviderRequestMessages({
  1483. entries: [...retainedToolRun(), ...compactionAttachments()],
  1484. useMidConversationSystem: false,
  1485. ...FOLD,
  1486. }).messages;
  1487. expect(messages.slice(2)).toEqual([
  1488. toolResult("1\tB"),
  1489. user(`${wrap(called)}\n`),
  1490. user(wrap(result)),
  1491. user(wrap(note)),
  1492. user(wrap("env body")),
  1493. ]);
  1494. });
  1495. // 旧版本写的补回是一条(调用说明和结果用 \n 相连),来源相同,冷恢复后同样在 user 侧。
  1496. it("projects an old single restore entry user-side and unfolded", () => {
  1497. const messages = buildProviderRequestMessages({
  1498. entries: [
  1499. ...retainedToolRun(),
  1500. attachment("resume_referenced_session_context", `${called}\n${result}`),
  1501. ],
  1502. ...FOLD,
  1503. }).messages;
  1504. expect(messages.slice(2)).toEqual([toolResult("1\tB"), user(wrap(`${called}\n${result}`))]);
  1505. });
  1506. it("ends the summary with a newline when restored bodies follow it", () => {
  1507. const messages = buildProviderRequestMessages({
  1508. entries: [
  1509. {
  1510. message: user("Summary:\nA"),
  1511. metadata: { source: "legacy_synthetic", compactBoundary: { boundaryId: "b1" } },
  1512. },
  1513. ...compactionAttachments(),
  1514. ],
  1515. ...FOLD,
  1516. }).messages;
  1517. expect(messages).toEqual([
  1518. user("Summary:\nA\n"),
  1519. user(`${wrap(called)}\n`),
  1520. user(wrap(result)),
  1521. { role: "system", content: `${note}\n\nenv body` },
  1522. ]);
  1523. });
  1524. });