total-tokens-reminder.test.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. import { mkdtemp, rm } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { beforeEach, describe, expect, it, onTestFinished } from "vitest";
  5. import {
  6. createProjectId,
  7. createRootTraceContext,
  8. createSessionId,
  9. ModelErrorCode,
  10. type ModelInputMessage,
  11. type ModelRequest,
  12. type RuntimeInputPresentation,
  13. } from "@zcode/contracts";
  14. import { createSqliteSessionStore } from "../../adapters/src/storage/session-store/sqlite-session-store.js";
  15. import {
  16. TOTAL_TOKENS_SYSTEM_LINE,
  17. formatTotalTokensReminder,
  18. } from "../src/context/total-tokens.js";
  19. import { createSubagentContextBuilder } from "../src/subagent/context-builder.js";
  20. import type { AgentRuntimeInternal } from "../src/runtime/internal.js";
  21. import {
  22. consumeTotalTokensBudget,
  23. createTotalTokensBudgetState,
  24. decideTotalTokensReminder,
  25. reanchorTotalTokensBudget,
  26. rollOverTotalTokensBudget,
  27. } from "../src/runtime/helpers/total-tokens-budget.js";
  28. import { createToolRegistry } from "../src/tool/registry.js";
  29. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  30. import { createTestModelFactory } from "./test-runtime-model.js";
  31. import { createTestSessionEventStore } from "./test-event-store.js";
  32. import { createRecordingSubagentSessionStore } from "./subagent-test-store.js";
  33. // 开关默认关闭,每个 runtime 创建时从 runtimeConfig.totalTokensReminder.enabled 读一次。
  34. // 本文件默认在新建 runtime 时打开;undefined 表示不传配置,验证缺省关闭。
  35. const reminderSwitch: { enabled: boolean | undefined } = { enabled: true };
  36. beforeEach(() => {
  37. reminderSwitch.enabled = true;
  38. });
  39. function reminderConfig(): { totalTokensReminder?: { enabled: boolean } } {
  40. return reminderSwitch.enabled === undefined
  41. ? {}
  42. : { totalTokensReminder: { enabled: reminderSwitch.enabled } };
  43. }
  44. const SUMMARY_MARKER = "create a detailed summary";
  45. const REMINDER_PATTERN = /<total_tokens>(\d+) tokens left<\/total_tokens>/g;
  46. // 开关关闭时,默认 system 的动态段以 `# Memory, notes and feedback` 段结尾。
  47. const DEFAULT_SYSTEM_END = "work from the context, not intermediate files.";
  48. /** 一次主循环响应:工具调用或文本结束,usage 决定下一次提醒的数值。 */
  49. interface ScriptStep {
  50. input: number;
  51. output: number;
  52. tool?: boolean;
  53. /** 本次请求先报上下文超限,触发 reactive compaction 后重试同一步。 */
  54. exceed?: boolean;
  55. /** 缓存读写量。input 已经包含这两项(与 adapter 的 inputTokens 口径相同)。 */
  56. cacheRead?: number;
  57. cacheWrite?: number;
  58. /** 本次响应返回前送进的 guide;不带 presentation 的和信箱一样直接调 steerTurn。 */
  59. guides?: { input: string; inputPresentation?: RuntimeInputPresentation }[];
  60. }
  61. function contentText(content: ModelInputMessage["content"]): string {
  62. return typeof content === "string" ? content : JSON.stringify(content);
  63. }
  64. /** 请求里非前导 system 部分出现的全部提醒数值,按出现顺序。 */
  65. function reminderValues(request: ModelRequest): number[] {
  66. const firstNonSystem = request.messages.findIndex((message) => message.role !== "system");
  67. const body = request.messages
  68. .slice(firstNonSystem)
  69. .map((message) => contentText(message.content))
  70. .join("\n");
  71. return [...body.matchAll(REMINDER_PATTERN)].map((match) => Number(match[1]));
  72. }
  73. function leadingSystemText(request: ModelRequest): string {
  74. const firstNonSystem = request.messages.findIndex((message) => message.role !== "system");
  75. return request.messages
  76. .slice(0, firstNonSystem)
  77. .map((message) => contentText(message.content))
  78. .join("");
  79. }
  80. /**
  81. * 后台通知开启的新一轮:首个请求不收集,工具批次后收集但不重新起算。
  82. * 真实用户消息会把 rolled 和旧 anchor 一起抵消;只有这类轮次能观察到计数器本身的状态。
  83. */
  84. function runNotificationTurn(runtime: ReturnType<typeof createTestAgentRuntime>) {
  85. return runtime.executeTurn("<task-notification>background done</task-notification>", undefined, {
  86. inputSource: "background_task",
  87. inputVisibility: "model-only",
  88. inputPresentation: "task_notification",
  89. });
  90. }
  91. async function fixture(
  92. options: {
  93. mcs?: boolean;
  94. taskType?: "subagent_child" | "workflow_child";
  95. /** 小上下文窗口:上下文接近 50000 时触发 auto compaction。 */
  96. smallWindow?: boolean;
  97. } = {},
  98. ) {
  99. const root = await mkdtemp(join(tmpdir(), "total-tokens-reminder-"));
  100. const dbPath = join(root, "session.sqlite");
  101. let store = await createSqliteSessionStore({ dbPath });
  102. const sessionId = createSessionId("total-tokens-reminder");
  103. const mainRequests: ModelRequest[] = [];
  104. const summaryRequests: ModelRequest[] = [];
  105. const script: ScriptStep[] = [];
  106. const runtimes: ReturnType<typeof createTestAgentRuntime>[] = [];
  107. onTestFinished(async () => {
  108. for (const runtime of runtimes) await runtime.closeBrowserSession();
  109. store.close();
  110. await rm(root, { recursive: true, force: true });
  111. });
  112. await store.createSession({
  113. id: sessionId,
  114. projectID: createProjectId("test"),
  115. slug: "test",
  116. title: "test",
  117. directory: root,
  118. version: "test",
  119. });
  120. let toolCallIndex = 0;
  121. const modelFactory = createTestModelFactory({
  122. properties: { supportsMidConversationSystem: options.mcs === true },
  123. async generateText(request) {
  124. if (JSON.stringify(request.messages).includes(SUMMARY_MARKER)) {
  125. summaryRequests.push(request);
  126. return { text: "<summary>Continue the task.</summary>", finishReason: "stop", usage: {} };
  127. }
  128. mainRequests.push(request);
  129. const step = script[0];
  130. if (!step) throw new Error("script exhausted");
  131. if (step.exceed) {
  132. step.exceed = false;
  133. throw Object.assign(new Error("provider context window exceeded"), {
  134. code: ModelErrorCode.ModelContextExceeded,
  135. });
  136. }
  137. script.shift();
  138. const runtime = runtimes.at(-1)!;
  139. for (const guide of step.guides ?? []) {
  140. const queued = await runtime.steerTurn({
  141. delivery: "guide",
  142. expectedTurnId: runtime.getActiveTurnInfo()?.turnId,
  143. ...guide,
  144. });
  145. expect(queued.kind).toBe("queued");
  146. }
  147. const usage = {
  148. inputTokens: step.input,
  149. outputTokens: step.output,
  150. totalTokens: step.input + step.output,
  151. ...(step.cacheRead !== undefined ? { cacheReadTokens: step.cacheRead } : {}),
  152. ...(step.cacheWrite !== undefined ? { cacheWriteTokens: step.cacheWrite } : {}),
  153. };
  154. if (!step.tool) return { text: "done", finishReason: "stop", usage };
  155. toolCallIndex += 1;
  156. return {
  157. text: "",
  158. finishReason: "tool-calls",
  159. toolCalls: [{ id: `inspect-${toolCallIndex}`, name: "Inspect", input: {} }],
  160. usage,
  161. };
  162. },
  163. });
  164. const makeRuntime = () => {
  165. const registry = createToolRegistry();
  166. registry.register({
  167. inputSchema: {},
  168. metadata: {
  169. name: "Inspect",
  170. concurrentSafe: true,
  171. destructive: false,
  172. needsApproval: false,
  173. readOnly: true,
  174. riskLevel: "low",
  175. sideEffectScope: "none",
  176. },
  177. handler: async () => "ok",
  178. });
  179. const runtime = createTestAgentRuntime(
  180. sessionId,
  181. {
  182. mode: "yolo",
  183. maxTurns: 30,
  184. modelStreaming: "off",
  185. taskType: options.taskType,
  186. titleGeneration: { enabled: false },
  187. workspacePath: root,
  188. ...reminderConfig(),
  189. ...(options.smallWindow
  190. ? {
  191. compact: { bufferTokens: 10, contextWindow: 50_000, summaryReserveTokens: 0 },
  192. maxOutputTokens: 1,
  193. }
  194. : {}),
  195. },
  196. {
  197. eventStore: createTestSessionEventStore(),
  198. modelFactory,
  199. sessionStore: store,
  200. toolRegistry: registry,
  201. },
  202. );
  203. runtimes.push(runtime);
  204. return { runtime, internal: runtime as unknown as AgentRuntimeInternal };
  205. };
  206. return {
  207. ...makeRuntime(),
  208. mainRequests,
  209. summaryRequests,
  210. script(...steps: ScriptStep[]) {
  211. script.push(...steps);
  212. },
  213. async reopen() {
  214. store.close();
  215. store = await createSqliteSessionStore({ dbPath });
  216. const next = makeRuntime();
  217. await next.runtime.resumeFromStore();
  218. return next;
  219. },
  220. };
  221. }
  222. describe("total-tokens budget math", () => {
  223. it("formats the fixed budget line", () => {
  224. expect(TOTAL_TOKENS_SYSTEM_LINE).toBe("<total_tokens>15000000 tokens left</total_tokens>");
  225. expect(formatTotalTokensReminder(14998995)).toBe(
  226. "<total_tokens>14998995 tokens left</total_tokens>",
  227. );
  228. });
  229. it("counts growth since the anchor, adds rollovers, never goes up and stops at zero", () => {
  230. let state = reanchorTotalTokensBudget(createTotalTokensBudgetState(), 40_000);
  231. let step = consumeTotalTokensBudget(state, 40_000);
  232. expect(step.remaining).toBe(15_000_000);
  233. step = consumeTotalTokensBudget(step.state, 52_000);
  234. expect(step.remaining).toBe(14_988_000);
  235. // 上下文变小(例如 microcompact)时数值不回升。
  236. step = consumeTotalTokensBudget(step.state, 30_000);
  237. expect(step.remaining).toBe(14_988_000);
  238. state = rollOverTotalTokensBudget(step.state, 180_000);
  239. step = consumeTotalTokensBudget(state, 30_000);
  240. expect(step.remaining).toBe(15_000_000 - (180_000 + 30_000 - 40_000));
  241. step = consumeTotalTokensBudget(reanchorTotalTokensBudget(step.state, 30_000), 30_000);
  242. expect(step.remaining).toBe(15_000_000);
  243. expect(consumeTotalTokensBudget(createTotalTokensBudgetState(), 16_000_000).remaining).toBe(0);
  244. });
  245. it.each([
  246. ["turn_input", true, true, { emit: true, reanchor: true }],
  247. ["turn_input", true, false, { emit: false, reanchor: false }],
  248. ["turn_input", false, true, { emit: false, reanchor: false }],
  249. ["tool_batch", true, false, { emit: true, reanchor: false }],
  250. ["tool_batch", false, false, { emit: true, reanchor: false }],
  251. ["text_guide", true, true, { emit: true, reanchor: true }],
  252. ["text_guide", true, false, { emit: true, reanchor: false }],
  253. ["text_guide", false, true, { emit: true, reanchor: false }],
  254. ] as const)(
  255. "decides reason=%s main=%s fromUser=%s",
  256. (reason, mainSession, fromUser, expected) => {
  257. expect(decideTotalTokensReminder({ reason, mainSession, fromUser })).toEqual(expected);
  258. },
  259. );
  260. });
  261. describe("total-tokens reminder in the turn loop", () => {
  262. it.each([{ mcs: false }, { mcs: true }])(
  263. "counts down within a turn, re-anchors on the next prompt and replays after resume %j",
  264. async ({ mcs }) => {
  265. const f = await fixture({ mcs });
  266. f.script(
  267. { input: 1000, output: 5, tool: true },
  268. { input: 2400, output: 7, tool: true },
  269. { input: 2600, output: 9 },
  270. );
  271. await f.runtime.executeTurn("first prompt");
  272. expect(f.mainRequests.map(reminderValues)).toEqual([
  273. [15_000_000],
  274. [15_000_000, 14_998_995],
  275. [15_000_000, 14_998_995, 14_997_593],
  276. ]);
  277. expect(
  278. leadingSystemText(f.mainRequests[0]!).endsWith(`\n\n${TOTAL_TOKENS_SYSTEM_LINE}`),
  279. ).toBe(true);
  280. if (mcs) {
  281. // MCS 下首个请求的提醒并入对话中的同一条 system,排在日期之前。
  282. const request = f.mainRequests[0]!;
  283. const firstNonSystem = request.messages.findIndex((message) => message.role !== "system");
  284. const merged = request.messages
  285. .slice(firstNonSystem)
  286. .find(
  287. (message) =>
  288. message.role === "system" &&
  289. contentText(message.content).includes(TOTAL_TOKENS_SYSTEM_LINE),
  290. );
  291. expect(contentText(merged!.content)).toContain(
  292. `${TOTAL_TOKENS_SYSTEM_LINE}\n\nToday's date is`,
  293. );
  294. }
  295. // 下一条真实用户消息以上一轮最后一次响应(2609)为起点。
  296. f.script({ input: 3000, output: 10, tool: true }, { input: 3100, output: 3 });
  297. await f.runtime.executeTurn("second prompt");
  298. expect(f.mainRequests.slice(3).map(reminderValues)).toEqual([
  299. [15_000_000, 14_998_995, 14_997_593, 15_000_000],
  300. [15_000_000, 14_998_995, 14_997_593, 15_000_000, 14_999_599],
  301. ]);
  302. // 冷恢复:已发提醒原样回放;计数器从零开始,下一条真实消息用持久化的 usage(3103)起算。
  303. const cold = await f.reopen();
  304. f.script({ input: 3200, output: 4, tool: true }, { input: 3300, output: 1 });
  305. await cold.runtime.executeTurn("after resume");
  306. const resumed = f.mainRequests.slice(5).map(reminderValues);
  307. expect(resumed).toEqual([
  308. [15_000_000, 14_998_995, 14_997_593, 15_000_000, 14_999_599, 15_000_000],
  309. [15_000_000, 14_998_995, 14_997_593, 15_000_000, 14_999_599, 15_000_000, 14_999_899],
  310. ]);
  311. },
  312. );
  313. it("adds the pre-compaction context on reactive compaction and adds no reminder to the retry", async () => {
  314. const f = await fixture();
  315. // 第一轮留下可摘要的历史;第二轮工具批次之后的请求超限。
  316. f.script({ input: 1000, output: 5, tool: true }, { input: 1100, output: 5 });
  317. await f.runtime.executeTurn("build history");
  318. f.script(
  319. { input: 1300, output: 5, tool: true },
  320. { input: 500, output: 5, tool: true, exceed: true },
  321. { input: 600, output: 2 },
  322. );
  323. await f.runtime.executeTurn("compact during the turn");
  324. expect(f.summaryRequests).toHaveLength(1);
  325. const values = f.mainRequests.slice(2).map(reminderValues);
  326. // 轮首以 1105 起算;工具批次后 1305 - 1105 = 200。
  327. expect(values[0]!.at(-1)).toBe(15_000_000);
  328. expect(values[1]!.at(-1)).toBe(14_999_800);
  329. // 摘要请求不产生新提醒:它只含被摘要的历史,超限前刚收集的那条在保留的尾部里。
  330. expect(reminderValues(f.summaryRequests[0]!)).toEqual(values[1]!.slice(0, -1));
  331. // compaction 后的重试不收集:最后一条仍是 compaction 前收集的那条,且只有一条。
  332. expect(values[2]!.at(-1)).toBe(14_999_800);
  333. expect(values[2]!.filter((value) => value === 14_999_800)).toHaveLength(1);
  334. // 下一个工具批次:rolled 1305 + 当前 505 - anchor 1105 = 705。
  335. expect(values[3]!.at(-1)).toBe(15_000_000 - 705);
  336. });
  337. it("adds the pre-compaction context on auto compaction after a tool batch", async () => {
  338. const f = await fixture({ smallWindow: true });
  339. f.script({ input: 1000, output: 5 });
  340. await f.runtime.executeTurn("build history");
  341. f.script(
  342. { input: 1200, output: 5, tool: true },
  343. // 这次响应后上下文到 49995,下一次请求前触发 auto compaction。
  344. { input: 49_990, output: 5, tool: true },
  345. { input: 600, output: 5, tool: true },
  346. { input: 700, output: 1 },
  347. );
  348. await f.runtime.executeTurn("compact during the turn");
  349. expect(f.summaryRequests).toHaveLength(1);
  350. const values = f.mainRequests.slice(1).map(reminderValues);
  351. // 轮首以 1005 起算;第一个工具批次后 1205 - 1005 = 200。
  352. expect(values[0]!.at(-1)).toBe(15_000_000);
  353. expect(values[1]!.at(-1)).toBe(15_000_000 - 200);
  354. // compaction 前收集的这条落在保留的尾部:摘要请求只含被摘要的历史,不含它,也不新增;
  355. // compaction 后的首个请求也不新增。
  356. expect(reminderValues(f.summaryRequests[0]!)).toEqual(values[1]);
  357. expect(values[2]!.at(-1)).toBe(15_000_000 - 48_990);
  358. expect(values[2]!.filter((value) => value === 15_000_000 - 48_990)).toHaveLength(1);
  359. // 下一个工具批次:rolled 49995 + 当前 605 - anchor 1005 = 49595;不累加时仍停在 48990。
  360. expect(values[3]!.at(-1)).toBe(15_000_000 - 49_595);
  361. });
  362. it("does not add the context of a manual compaction", async () => {
  363. const f = await fixture();
  364. f.script({ input: 1000, output: 5, tool: true }, { input: 1200, output: 5 });
  365. await f.runtime.executeTurn("before manual compaction");
  366. const result = await f.internal.compactActiveConversation(
  367. undefined,
  368. createRootTraceContext(),
  369. [],
  370. {},
  371. );
  372. expect(result.outcome).toBe("compacted");
  373. // 通知轮不重新起算,计数器沿用第一轮的 anchor 0 与已用 1005。
  374. f.script({ input: 3000, output: 5, tool: true }, { input: 3100, output: 1 });
  375. await runNotificationTurn(f.runtime);
  376. const notification = f.mainRequests.slice(2, 4).map(reminderValues);
  377. expect(notification[0]).toEqual([]);
  378. // 未累加:used = max(1005, 0 + 3005 - 0) = 3005;若手动 compaction 累加了 1205,会是 4210。
  379. expect(notification[1]).toEqual([15_000_000 - 3005]);
  380. // 下一条真实消息重新起算,以通知轮最后一次响应(3101)为起点。
  381. f.script({ input: 3300, output: 4, tool: true }, { input: 3400, output: 1 });
  382. await f.runtime.executeTurn("after manual compaction");
  383. const values = f.mainRequests.slice(4).map(reminderValues);
  384. expect(values[0]!.at(-1)).toBe(15_000_000);
  385. expect(values[1]!.at(-1)).toBe(15_000_000 - 203);
  386. });
  387. it("resets the counter when the same runtime resumes again", async () => {
  388. const f = await fixture();
  389. f.script({ input: 1000, output: 5 });
  390. await f.runtime.executeTurn("first prompt");
  391. // 第二条真实消息把 anchor 移到 1005。
  392. f.script({ input: 2000, output: 5 });
  393. await f.runtime.executeTurn("second prompt");
  394. // bootstrap 复用同一个 runtime 再次恢复;恢复等同新会话启动。
  395. await f.runtime.resumeFromStore();
  396. f.script({ input: 3000, output: 5, tool: true }, { input: 3100, output: 1 });
  397. await runNotificationTurn(f.runtime);
  398. const notification = f.mainRequests.slice(2).map(reminderValues);
  399. expect(notification[0]!.at(-1)).toBe(15_000_000);
  400. // 清零后从 0 计数:used = 3005;若沿用恢复前的 anchor 1005,会是 2000。
  401. expect(notification[1]!.at(-1)).toBe(15_000_000 - 3005);
  402. });
  403. it("gives a goal continuation no reminder on its first request and keeps the anchor", async () => {
  404. const f = await fixture();
  405. f.script({ input: 1000, output: 5 });
  406. await f.runtime.executeTurn("set the goal");
  407. f.script({ input: 2000, output: 5, tool: true }, { input: 2100, output: 1 });
  408. await f.runtime.executeTurn("continue the goal", undefined, {
  409. inputSource: "goal-continuation",
  410. inputVisibility: "model-only",
  411. });
  412. const values = f.mainRequests.slice(1).map(reminderValues);
  413. // 首个请求只带上一轮的那条提醒。
  414. expect(values[0]).toEqual([15_000_000]);
  415. // 不重新起算:anchor 仍是 0,used = 2005;重新起算会是 2005 - 1005 = 1000。
  416. expect(values[1]).toEqual([15_000_000, 15_000_000 - 2005]);
  417. });
  418. it.each([
  419. { name: "a session mailbox guide", guides: [{ input: "mailbox note" }], reanchor: false },
  420. {
  421. name: "a user guide",
  422. guides: [{ input: "user note", inputPresentation: "user_steer" as const }],
  423. reanchor: true,
  424. },
  425. {
  426. name: "a mailbox guide drained with a user guide",
  427. guides: [
  428. { input: "mailbox note" },
  429. { input: "user note", inputPresentation: "user_steer" as const },
  430. ],
  431. reanchor: true,
  432. },
  433. ])("re-anchors after a text-only reply only for a user guide: $name", async (testCase) => {
  434. const f = await fixture();
  435. f.script({ input: 1000, output: 5, guides: testCase.guides }, { input: 1100, output: 2 });
  436. await f.runtime.executeTurn("first prompt");
  437. // 轮首以 0 起算;纯文本回复后上下文 1005,不重新起算时 used = 1005。
  438. expect(f.mainRequests.map(reminderValues)).toEqual([
  439. [15_000_000],
  440. [15_000_000, testCase.reanchor ? 15_000_000 : 15_000_000 - 1005],
  441. ]);
  442. });
  443. it("counts cache tokens once because the input already includes them", async () => {
  444. const f = await fixture();
  445. f.script(
  446. { input: 1000, output: 5, tool: true, cacheRead: 800, cacheWrite: 100 },
  447. { input: 1100, output: 2 },
  448. );
  449. await f.runtime.executeTurn("cached prompt");
  450. // 上下文是 input + output = 1005;再加一次缓存读写会是 1905。
  451. expect(f.mainRequests.map(reminderValues)).toEqual([
  452. [15_000_000],
  453. [15_000_000, 15_000_000 - 1005],
  454. ]);
  455. });
  456. it("gives a subagent no reminder on its first request and counts its whole context", async () => {
  457. const f = await fixture({ taskType: "subagent_child" });
  458. f.script({ input: 1000, output: 5, tool: true }, { input: 1100, output: 2 });
  459. await f.runtime.executeTurn("child task");
  460. expect(f.mainRequests.map(reminderValues)).toEqual([[], [14_998_995]]);
  461. });
  462. it("keeps the budget line for a workflow child and never re-anchors it", async () => {
  463. const f = await fixture({ taskType: "workflow_child" });
  464. f.script({ input: 1000, output: 5, tool: true }, { input: 1100, output: 2 });
  465. await f.runtime.executeTurn("workflow step");
  466. expect(leadingSystemText(f.mainRequests[0]!).endsWith(`\n\n${TOTAL_TOKENS_SYSTEM_LINE}`)).toBe(
  467. true,
  468. );
  469. expect(f.mainRequests.map(reminderValues)).toEqual([[], [14_998_995]]);
  470. });
  471. });
  472. describe("total-tokens system line", () => {
  473. it("ends the subagent system prompt after the notes", () => {
  474. const built = createSubagentContextBuilder({
  475. agentPrompt: "You are a file search specialist.",
  476. envInfo: {
  477. cwd: "/Users/dev/project",
  478. platform: "darwin",
  479. shell: "zsh",
  480. osVersion: "Darwin 24.3.0",
  481. nodeVersion: "24.14.0",
  482. isGitRepository: false,
  483. },
  484. totalTokensReminder: true,
  485. }).build();
  486. const tail = String(built.systemMessages.at(-1)?.content);
  487. expect(tail.endsWith(`this note is about report files.)\n\n${TOTAL_TOKENS_SYSTEM_LINE}`)).toBe(
  488. true,
  489. );
  490. });
  491. });
  492. /** 去掉缓存断点:断点只标在最新的消息上,会随新请求移动,不是消息内容。 */
  493. function withoutCacheControl(messages: ModelInputMessage[]): ModelInputMessage[] {
  494. return messages.map(({ cacheControl: _cacheControl, ...message }) => message);
  495. }
  496. function hasTotalTokensText(request: ModelRequest): boolean {
  497. return JSON.stringify(request.messages).includes("<total_tokens>");
  498. }
  499. describe("total-tokens reminder off by default", () => {
  500. beforeEach(() => {
  501. // 不传配置:缺省就是关闭。
  502. reminderSwitch.enabled = undefined;
  503. });
  504. it.each([{ mcs: false }, { mcs: true }])(
  505. "adds no budget line and no reminder to a main session, also after resume %j",
  506. async ({ mcs }) => {
  507. const f = await fixture({ mcs });
  508. f.script(
  509. { input: 1000, output: 5, tool: true },
  510. { input: 2400, output: 7, tool: true },
  511. { input: 2600, output: 9 },
  512. );
  513. await f.runtime.executeTurn("first prompt");
  514. f.script({ input: 3000, output: 10, tool: true }, { input: 3100, output: 3 });
  515. await f.runtime.executeTurn("second prompt");
  516. const cold = await f.reopen();
  517. f.script({ input: 3200, output: 4, tool: true }, { input: 3300, output: 1 });
  518. await cold.runtime.executeTurn("after resume");
  519. expect(f.mainRequests).toHaveLength(7);
  520. for (const request of f.mainRequests) {
  521. expect(hasTotalTokensText(request)).toBe(false);
  522. expect(leadingSystemText(request).endsWith(DEFAULT_SYSTEM_END)).toBe(true);
  523. }
  524. },
  525. );
  526. it.each(["subagent_child", "workflow_child"] as const)(
  527. "adds no budget line and no reminder to a %s",
  528. async (taskType) => {
  529. const f = await fixture({ taskType });
  530. f.script({ input: 1000, output: 5, tool: true }, { input: 1100, output: 2 });
  531. await f.runtime.executeTurn("child task");
  532. expect(f.mainRequests).toHaveLength(2);
  533. for (const request of f.mainRequests) expect(hasTotalTokensText(request)).toBe(false);
  534. },
  535. );
  536. it("ends the subagent system prompt with the notes", () => {
  537. const built = createSubagentContextBuilder({
  538. agentPrompt: "You are a file search specialist.",
  539. envInfo: {
  540. cwd: "/Users/dev/project",
  541. platform: "darwin",
  542. shell: "zsh",
  543. osVersion: "Darwin 24.3.0",
  544. nodeVersion: "24.14.0",
  545. isGitRepository: false,
  546. },
  547. }).build();
  548. const tail = String(built.systemMessages.at(-1)?.content);
  549. expect(tail.endsWith("this note is about report files.)")).toBe(true);
  550. expect(JSON.stringify(built.systemMessages)).not.toContain("<total_tokens>");
  551. });
  552. it("replays stored reminders unchanged and keeps the snapshot line until the next compaction", async () => {
  553. // 开关打开时写下的会话:提醒已落库,prompt 快照带预算行。
  554. reminderSwitch.enabled = true;
  555. const f = await fixture();
  556. f.script({ input: 1000, output: 5, tool: true }, { input: 1100, output: 2 });
  557. await f.runtime.executeTurn("written while on");
  558. const lastLive = f.mainRequests.at(-1)!;
  559. expect(reminderValues(lastLive)).toEqual([15_000_000, 14_998_995]);
  560. reminderSwitch.enabled = false;
  561. const cold = await f.reopen();
  562. f.script({ input: 1200, output: 5, tool: true }, { input: 1300, output: 2 });
  563. await cold.runtime.executeTurn("after the switch is off");
  564. const resumed = f.mainRequests.slice(2);
  565. // 已发的提醒按原位置、原字节回放,不新增;已发的消息只追加。
  566. for (const request of resumed) {
  567. expect(reminderValues(request)).toEqual([15_000_000, 14_998_995]);
  568. expect(withoutCacheControl(request.messages.slice(0, lastLive.messages.length))).toEqual(
  569. withoutCacheControl(lastLive.messages),
  570. );
  571. // 快照里记录的预算行保留到下一次压缩,system 字节不变。
  572. expect(leadingSystemText(request)).toBe(leadingSystemText(lastLive));
  573. }
  574. const result = await cold.internal.compactActiveConversation(
  575. undefined,
  576. createRootTraceContext(),
  577. [],
  578. {},
  579. );
  580. expect(result.outcome).toBe("compacted");
  581. f.script({ input: 1400, output: 5, tool: true }, { input: 1500, output: 2 });
  582. await cold.runtime.executeTurn("after compaction");
  583. for (const request of f.mainRequests.slice(4)) {
  584. expect(leadingSystemText(request)).not.toContain("<total_tokens>");
  585. expect(leadingSystemText(request).endsWith(DEFAULT_SYSTEM_END)).toBe(true);
  586. expect(reminderValues(request)).toEqual([]);
  587. }
  588. });
  589. });
  590. describe("total-tokens reminder value per runtime", () => {
  591. it("keeps a snapshot without the line when turned on at resume and adds the line after compaction", async () => {
  592. // 关闭时写下的会话:没有提醒,prompt 快照没有预算行。
  593. reminderSwitch.enabled = false;
  594. const f = await fixture();
  595. f.script({ input: 1000, output: 5, tool: true }, { input: 1100, output: 2 });
  596. await f.runtime.executeTurn("written while off");
  597. const lastLive = f.mainRequests.at(-1)!;
  598. expect(hasTotalTokensText(lastLive)).toBe(false);
  599. reminderSwitch.enabled = true;
  600. const cold = await f.reopen();
  601. f.script({ input: 1200, output: 5, tool: true }, { input: 1300, output: 2 });
  602. await cold.runtime.executeTurn("after the switch is on");
  603. const resumed = f.mainRequests.slice(2);
  604. // 倒数提醒按当前值收集:真实消息以持久化的 usage(1102)起算,工具批次后 used = 1205 - 1102。
  605. expect(resumed.map(reminderValues)).toEqual([[15_000_000], [15_000_000, 14_999_897]]);
  606. for (const request of resumed) {
  607. // system 按快照原字节发送,不补预算行;已发的消息只追加。
  608. expect(leadingSystemText(request)).toBe(leadingSystemText(lastLive));
  609. expect(withoutCacheControl(request.messages.slice(0, lastLive.messages.length))).toEqual(
  610. withoutCacheControl(lastLive.messages),
  611. );
  612. }
  613. const result = await cold.internal.compactActiveConversation(
  614. undefined,
  615. createRootTraceContext(),
  616. [],
  617. {},
  618. );
  619. expect(result.outcome).toBe("compacted");
  620. f.script({ input: 1400, output: 5 });
  621. await cold.runtime.executeTurn("after compaction");
  622. // 压缩清掉快照,重建的 system 以预算行结尾。
  623. const afterCompaction = f.mainRequests.at(-1)!;
  624. expect(leadingSystemText(afterCompaction).endsWith(`\n\n${TOTAL_TOKENS_SYSTEM_LINE}`)).toBe(
  625. true,
  626. );
  627. expect(reminderValues(afterCompaction).at(-1)).toBe(15_000_000);
  628. });
  629. it.each([true, false])("a subagent follows the parent runtime value %s", async (enabled) => {
  630. const usage = { inputTokens: 1, outputTokens: 1, totalTokens: 2 };
  631. const childRequests: ModelRequest[] = [];
  632. let parentCalls = 0;
  633. const runtime = createTestAgentRuntime(
  634. createSessionId(`total-tokens-child-${enabled}`),
  635. {
  636. mode: "yolo",
  637. workingDirectory: "/workspace/project",
  638. totalTokensReminder: { enabled },
  639. subagents: {
  640. profiles: [
  641. {
  642. name: "count-child",
  643. description: "Counts.",
  644. source: "project",
  645. systemPrompt: "Count as asked.",
  646. tools: ["Read"],
  647. },
  648. ],
  649. },
  650. },
  651. {
  652. eventStore: createTestSessionEventStore(),
  653. sessionStore: createRecordingSubagentSessionStore(),
  654. modelFactory: createTestModelFactory({
  655. async generateText(request) {
  656. if (!(request.tools ?? []).some((tool) => tool.name === "Agent")) {
  657. childRequests.push(request);
  658. return { text: "child done", finishReason: "stop", usage };
  659. }
  660. parentCalls += 1;
  661. if (parentCalls > 1) return { text: "parent done", finishReason: "stop", usage };
  662. return {
  663. text: "",
  664. finishReason: "tool-calls",
  665. toolCalls: [
  666. {
  667. id: "call_child",
  668. name: "Agent",
  669. input: {
  670. description: "Count",
  671. prompt: "Count to three.",
  672. subagent_type: "count-child",
  673. run_in_background: false,
  674. },
  675. },
  676. ],
  677. usage,
  678. };
  679. },
  680. }),
  681. },
  682. );
  683. onTestFinished(async () => {
  684. await runtime.closeBrowserSession();
  685. });
  686. await runtime.executeTurn("count");
  687. expect(childRequests).toHaveLength(1);
  688. expect(leadingSystemText(childRequests[0]!).includes(TOTAL_TOKENS_SYSTEM_LINE)).toBe(enabled);
  689. });
  690. });