token-estimation-regression.test.ts 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. import { describe, expect, it } from "vitest";
  2. import { ESTIMATED_TOKEN_CHAR_DIVISOR } from "@zcode/shared";
  3. import { estimateMessageTokens, shouldAutoCompact } from "../src/compact/index.js";
  4. import { estimateTokens } from "../src/context/utils.js";
  5. import { buildPostCompactFileRestore } from "../src/runtime/helpers/compact-post-reminders.js";
  6. import { createReadFileStatePathKey } from "../src/tool/read-file-state.js";
  7. import type { ReadFileStateMap } from "../src/tool/types.js";
  8. describe("token estimation regression", () => {
  9. it("uses the shared three-character divisor for text and model messages", () => {
  10. const text = "x".repeat(10);
  11. expect(estimateTokens(text)).toBe(4);
  12. expect(estimateMessageTokens([{ role: "user", content: text }])).toBe(4);
  13. });
  14. it("counts each tool call name and serialized input without counting its id", () => {
  15. const content = "assistant text";
  16. const toolCalls = [
  17. {
  18. id: "tool-id-must-not-be-counted-" + "x".repeat(120),
  19. name: "Read",
  20. input: {
  21. file_path: "/tmp/" + "nested/".repeat(12) + "large-input.txt",
  22. limit: 2_000,
  23. },
  24. },
  25. {
  26. id: "undefined-input",
  27. name: "Bash",
  28. input: undefined,
  29. },
  30. ];
  31. const estimatedCharacters =
  32. content.length +
  33. toolCalls.reduce(
  34. (total, toolCall) => total + (toolCall.name + JSON.stringify(toolCall.input ?? {})).length,
  35. 0,
  36. );
  37. expect(
  38. estimateMessageTokens([
  39. {
  40. role: "assistant",
  41. content,
  42. toolCalls,
  43. },
  44. ]),
  45. ).toBe(Math.ceil(estimatedCharacters / ESTIMATED_TOKEN_CHAR_DIVISOR));
  46. });
  47. it("falls back to an empty object for non-JSON-safe tool call inputs", () => {
  48. const circularInput: Record<string, unknown> = {};
  49. circularInput.self = circularInput;
  50. const toolCalls = [
  51. { id: "bigint-input", name: "BigIntTool", input: 1n },
  52. { id: "circular-input", name: "CircularTool", input: circularInput },
  53. ];
  54. const estimatedCharacters = toolCalls.reduce(
  55. (total, toolCall) => total + `${toolCall.name}{}`.length,
  56. 0,
  57. );
  58. expect(
  59. estimateMessageTokens([
  60. {
  61. role: "assistant",
  62. content: "",
  63. toolCalls,
  64. },
  65. ]),
  66. ).toBe(Math.ceil(estimatedCharacters / ESTIMATED_TOKEN_CHAR_DIVISOR));
  67. });
  68. it("uses tool call inputs in local auto-compact decisions", () => {
  69. const toolCall = {
  70. name: "Bash",
  71. input: { command: "x".repeat(300) },
  72. };
  73. const messages = [
  74. { role: "user", content: "old context" },
  75. { role: "assistant", content: "", toolCalls: [toolCall] },
  76. ];
  77. const estimatedTokenCount =
  78. Math.ceil(messages[0]!.content.length / ESTIMATED_TOKEN_CHAR_DIVISOR) +
  79. Math.ceil(
  80. (toolCall.name + JSON.stringify(toolCall.input)).length / ESTIMATED_TOKEN_CHAR_DIVISOR,
  81. );
  82. expect(
  83. shouldAutoCompact({
  84. config: {
  85. bufferTokens: 100,
  86. contextWindow: 200,
  87. maxOutputTokens: 1,
  88. },
  89. messages,
  90. }),
  91. ).toMatchObject({
  92. estimatedTokenCount,
  93. reason: "above_threshold",
  94. shouldCompact: true,
  95. tokenCount: estimatedTokenCount,
  96. tokenSource: "estimate",
  97. });
  98. });
  99. it("uses the shared divisor when deciding whether to inline post-compact read content", async () => {
  100. const filePath = "/tmp/zcode-compact-three-char-divisor.txt";
  101. const content = "x".repeat(31);
  102. const readFileState: ReadFileStateMap = new Map();
  103. readFileState.set(createReadFileStatePathKey(filePath), {
  104. content,
  105. isPartialView: false,
  106. path: filePath,
  107. readAt: new Date(5_000),
  108. sourceTool: "Read",
  109. });
  110. const restore = await buildPostCompactFileRestore({
  111. maxFileTokens: 10,
  112. readFiles: async () => [
  113. {
  114. output: { content, filePath, numLines: 1, startLine: 1, totalLines: 1, type: "text" },
  115. readFileStateEntry: {
  116. content,
  117. isPartialView: false,
  118. path: filePath,
  119. readAt: new Date(6_000),
  120. },
  121. type: "text",
  122. },
  123. ],
  124. readFileState,
  125. });
  126. const reminderText = JSON.stringify(restore.entries);
  127. expect(reminderText).toContain(`Note: ${filePath} was read before`);
  128. expect(reminderText).not.toContain(content);
  129. });
  130. });