token-estimator.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. /**
  2. * Token estimation for {@link ContextLifecycleManager}.
  3. *
  4. * Why this exists
  5. * ---------------
  6. * pi-agent-core's `estimateTokens` / `estimateContextTokens` use `Math.ceil(chars / 4)`,
  7. * which severely under-counts CJK text — Chinese characters consume 1–2 BPE tokens each,
  8. * so chars/4 (≈0.25 tokens/char) under-reports by 4–8×. Under-reporting moves the
  9. * compaction trigger to the right, past the point at which Messages-compatible
  10. * providers reject the request (e.g. minimax's MiniMax-M2.7: rejects when
  11. * input > contextWindow - max_tokens).
  12. *
  13. * Pluggable interface
  14. * -------------------
  15. * {@link TokenEstimator} is the seam we own at the cloud-runtime layer.
  16. * {@link ContextLifecycleManager.evaluateTrigger} and selectFirstKeptIndex both
  17. * route through it. A future `count_tokens`-API-backed estimator can drop in
  18. * via constructor injection without touching manager logic.
  19. *
  20. * Ground-truth-aware estimate
  21. * ---------------------------
  22. * `estimateContextTokens` preserves pi-agent-core's good pattern:
  23. * 1. Find the last successful assistant message with usage for the current context;
  24. * 2. Trust its provider-reported total as the prefix sum;
  25. * 3. Estimate only the trailing messages after that point.
  26. * This bounds estimator error to the trailing window — typically a handful of
  27. * messages — rather than the entire conversation.
  28. *
  29. * Default implementation
  30. * ----------------------
  31. * {@link BpeTokenEstimator} uses gpt-tokenizer's `o200k_base` (GPT-4o BPE) for
  32. * bounded word runs and a UTF-8 byte upper bound for oversized word runs or
  33. * tokenizer failures. o200k_base is not the provider tokenizer, but for MiniMax /
  34. * Messages-compatible endpoints it consistently over-estimates a touch (safe:
  35. * earlier trigger), which is the direction we want when capacity
  36. * miscalculation means a hard 4xx.
  37. *
  38. * Per-message structural overhead (4 tokens) accounts for role wrappers and
  39. * delimiters the provider injects around each turn — exact count varies by API
  40. * (Messages-compatible API vs. OpenAI ChatCompletions), but 4 is in the right
  41. * ballpark and again biased to over-estimate.
  42. *
  43. * Visual content (`image` and legacy/raw `video` blocks) is charged 4_800
  44. * tokens to match pi-agent-core's image stand-in; real visual-token counts
  45. * depend on media dimensions and the active provider.
  46. */
  47. import type { AgentMessage } from '@earendil-works/pi-agent-core';
  48. import { Buffer } from 'node:buffer';
  49. import { countTokens as countO200kBase } from 'gpt-tokenizer/model/gpt-4o';
  50. import type { ContextCompactionSummaryMessage } from './types.js';
  51. export interface ContextTokenEstimate {
  52. /** Estimated total tokens consumed by `messages`. */
  53. tokens: number;
  54. /**
  55. * Provider-reported usage at the last successful assistant message — the
  56. * ground-truth portion of `tokens`. `0` when no assistant usage was found.
  57. */
  58. usageTokens: number;
  59. /**
  60. * Estimator-computed token count for messages after `lastUsageIndex`. When
  61. * `lastUsageIndex` is `null`, this equals `tokens` (full estimate).
  62. */
  63. trailingTokens: number;
  64. /** Index of the assistant message whose usage block was used, or `null`. */
  65. lastUsageIndex: number | null;
  66. }
  67. export interface TokenEstimator {
  68. /** Estimate tokens for raw text without message structural overhead. */
  69. estimateTextTokens(text: string): number;
  70. /** Return the shared stand-in used for one model-visible image/video block. */
  71. estimateVisualTokens(): number;
  72. /** Estimate tokens for a single message. */
  73. estimateMessage(message: AgentMessage): number;
  74. /** Estimate tokens for an arbitrary sequence of messages (no ground truth). */
  75. estimateMessages(messages: AgentMessage[]): number;
  76. /**
  77. * Estimate context tokens for a transcript, preferring provider usage as the
  78. * prefix ground-truth. Mirrors pi-agent-core's `estimateContextTokens`
  79. * contract so existing call sites can swap implementations without changing
  80. * downstream interpretation.
  81. */
  82. estimateContextTokens(messages: AgentMessage[]): ContextTokenEstimate;
  83. }
  84. /** Per-message structural overhead (role wrapper + delimiters). */
  85. const MESSAGE_STRUCTURAL_OVERHEAD = 4;
  86. /** Stand-in token count for an image or legacy/raw video block. */
  87. const VISUAL_TOKEN_STAND_IN = 4_800;
  88. /** Pluggable encoder seam — tests inject deterministic encoders. */
  89. export type EncodeFn = (text: string) => number[] | Uint32Array;
  90. const MAX_EXACT_TOKENIZER_CHARS = 4_096;
  91. const UNICODE_LETTER_OR_NUMBER = /[\p{L}\p{N}]/u;
  92. function hasOversizedAlphanumericRun(text: string): boolean {
  93. let runLength = 0;
  94. for (const character of text) {
  95. const codePoint = character.codePointAt(0) ?? 0;
  96. const isLetterOrNumber =
  97. codePoint <= 0x7f
  98. ? (codePoint >= 0x30 && codePoint <= 0x39) ||
  99. (codePoint >= 0x41 && codePoint <= 0x5a) ||
  100. (codePoint >= 0x61 && codePoint <= 0x7a)
  101. : UNICODE_LETTER_OR_NUMBER.test(character);
  102. if (!isLetterOrNumber) {
  103. runLength = 0;
  104. continue;
  105. }
  106. runLength += 1;
  107. if (runLength > MAX_EXACT_TOKENIZER_CHARS) return true;
  108. }
  109. return false;
  110. }
  111. function estimateTextTokensUpperBound(text: string): number {
  112. return Buffer.byteLength(text, 'utf8');
  113. }
  114. function safeJsonStringify(value: unknown): string {
  115. try {
  116. return JSON.stringify(value) ?? 'undefined';
  117. } catch {
  118. return '[unserializable]';
  119. }
  120. }
  121. function isVisualContentBlock(block: { type?: unknown }): boolean {
  122. return block.type === 'image' || block.type === 'video';
  123. }
  124. function calculateContextTokens(usage: {
  125. input: number;
  126. output: number;
  127. cacheRead: number;
  128. cacheWrite: number;
  129. totalTokens: number;
  130. }): number {
  131. return usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
  132. }
  133. interface AssistantUsageRef {
  134. input: number;
  135. output: number;
  136. cacheRead: number;
  137. cacheWrite: number;
  138. totalTokens: number;
  139. }
  140. function getAssistantUsage(message: AgentMessage): AssistantUsageRef | undefined {
  141. if (message.role !== 'assistant') return undefined;
  142. const m = message as AgentMessage & {
  143. usage?: AssistantUsageRef;
  144. stopReason?: string;
  145. };
  146. if (m.stopReason === 'aborted' || m.stopReason === 'error') return undefined;
  147. return m.usage;
  148. }
  149. function getLastAssistantUsageInfo(
  150. messages: AgentMessage[],
  151. ): { usage: AssistantUsageRef; index: number } | undefined {
  152. let firstFreshIndex = 0;
  153. let compactedAt: number | undefined;
  154. for (let i = messages.length - 1; i >= 0; i -= 1) {
  155. if (messages[i]!.role !== 'compactionSummary') continue;
  156. const summary = messages[i] as ContextCompactionSummaryMessage;
  157. const keptCount = summary.keptMessageCount;
  158. if (keptCount !== undefined) {
  159. // Kept assistants appear AFTER the summary too. Only appended responses
  160. // describe the replacement context; their wall-clock timestamps may tie
  161. // or precede the summary if the clock changed.
  162. if (!Number.isSafeInteger(keptCount) || keptCount < 0) return undefined;
  163. firstFreshIndex = i + 1 + keptCount;
  164. } else {
  165. // Legacy persisted transcripts have no explicit retained-tail boundary.
  166. // Match the local runtime's conservative timestamp freshness rule.
  167. if (!Number.isFinite(summary.timestamp)) return undefined;
  168. compactedAt = summary.timestamp;
  169. firstFreshIndex = i + 1;
  170. }
  171. break;
  172. }
  173. for (let i = messages.length - 1; i >= firstFreshIndex; i -= 1) {
  174. const message = messages[i]!;
  175. if (
  176. compactedAt !== undefined &&
  177. (!Number.isFinite(message.timestamp) || message.timestamp <= compactedAt)
  178. ) {
  179. continue;
  180. }
  181. const usage = getAssistantUsage(message);
  182. if (usage) return { usage, index: i };
  183. }
  184. return undefined;
  185. }
  186. export class BpeTokenEstimator implements TokenEstimator {
  187. private readonly countExactTokens: (text: string) => number;
  188. /**
  189. * @param encoder Override the default o200k_base tokenizer. Tests inject
  190. * deterministic encoders (e.g. `text => text.split(' ')`); production passes
  191. * no argument so the default GPT-4o BPE token counter is used.
  192. *
  193. * The default wraps gpt-tokenizer with `allowedSpecial: 'all'`. Without it,
  194. * gpt-tokenizer defaults to `disallowedSpecial: 'all'` and THROWS on any
  195. * special-token literal (e.g. `<|endoftext|>`) appearing in transcript text.
  196. * Since this estimator runs inside the fail-closed `beforeLlmCall` checkpoint,
  197. * such a throw would abort the whole turn. We only count tokens, so treating
  198. * special-token literals as ordinary text is correct here.
  199. */
  200. constructor(encoder?: EncodeFn) {
  201. this.countExactTokens = encoder
  202. ? (text) => encoder(text).length
  203. : (text) => countO200kBase(text, { allowedSpecial: 'all' });
  204. }
  205. estimateTextTokens(text: string): number {
  206. if (!text) return 0;
  207. try {
  208. if (text.length > MAX_EXACT_TOKENIZER_CHARS && hasOversizedAlphanumericRun(text)) {
  209. return estimateTextTokensUpperBound(text);
  210. }
  211. const tokens = this.countExactTokens(text);
  212. return Number.isFinite(tokens) && tokens >= 0 ? tokens : estimateTextTokensUpperBound(text);
  213. } catch {
  214. return estimateTextTokensUpperBound(text);
  215. }
  216. }
  217. estimateVisualTokens(): number {
  218. return VISUAL_TOKEN_STAND_IN;
  219. }
  220. estimateMessage(message: AgentMessage): number {
  221. let tokens = MESSAGE_STRUCTURAL_OVERHEAD;
  222. switch (message.role) {
  223. case 'user': {
  224. const content = (message as Extract<AgentMessage, { role: 'user' }>).content;
  225. if (typeof content === 'string') {
  226. tokens += this.estimateTextTokens(content);
  227. } else if (Array.isArray(content)) {
  228. for (const block of content) {
  229. if (block.type === 'text' && block.text) {
  230. tokens += this.estimateTextTokens(block.text);
  231. } else if (isVisualContentBlock(block)) {
  232. tokens += this.estimateVisualTokens();
  233. }
  234. }
  235. }
  236. return tokens;
  237. }
  238. case 'assistant': {
  239. const assistant = message as Extract<AgentMessage, { role: 'assistant' }>;
  240. for (const block of assistant.content) {
  241. if (block.type === 'text') {
  242. tokens += this.estimateTextTokens(block.text);
  243. } else if (block.type === 'thinking') {
  244. tokens += this.estimateTextTokens((block as { thinking: string }).thinking);
  245. } else if (block.type === 'toolCall') {
  246. tokens += this.estimateTextTokens(block.name);
  247. tokens += this.estimateTextTokens(safeJsonStringify(block.arguments));
  248. }
  249. }
  250. return tokens;
  251. }
  252. case 'toolResult':
  253. case 'custom': {
  254. const content = (
  255. message as Extract<AgentMessage, { role: 'toolResult' | 'custom' }> & {
  256. content: string | Array<{ type: string; text?: string }>;
  257. }
  258. ).content;
  259. if (typeof content === 'string') {
  260. tokens += this.estimateTextTokens(content);
  261. } else if (Array.isArray(content)) {
  262. for (const block of content) {
  263. if (block.type === 'text' && typeof block.text === 'string') {
  264. tokens += this.estimateTextTokens(block.text);
  265. } else if (isVisualContentBlock(block)) {
  266. tokens += this.estimateVisualTokens();
  267. }
  268. }
  269. }
  270. return tokens;
  271. }
  272. case 'bashExecution': {
  273. const m = message as AgentMessage & { command?: string; output?: string };
  274. tokens += this.estimateTextTokens(m.command ?? '');
  275. tokens += this.estimateTextTokens(m.output ?? '');
  276. return tokens;
  277. }
  278. case 'branchSummary':
  279. case 'compactionSummary': {
  280. const m = message as AgentMessage & { summary?: string };
  281. tokens += this.estimateTextTokens(m.summary ?? '');
  282. return tokens;
  283. }
  284. }
  285. return tokens;
  286. }
  287. estimateMessages(messages: AgentMessage[]): number {
  288. let total = 0;
  289. for (const message of messages) {
  290. total += this.estimateMessage(message);
  291. }
  292. return total;
  293. }
  294. estimateContextTokens(messages: AgentMessage[]): ContextTokenEstimate {
  295. const info = getLastAssistantUsageInfo(messages);
  296. if (!info) {
  297. const trailing = this.estimateMessages(messages);
  298. return {
  299. tokens: trailing,
  300. usageTokens: 0,
  301. trailingTokens: trailing,
  302. lastUsageIndex: null,
  303. };
  304. }
  305. const usageTokens = calculateContextTokens(info.usage);
  306. let trailingTokens = 0;
  307. for (let i = info.index + 1; i < messages.length; i += 1) {
  308. trailingTokens += this.estimateMessage(messages[i]!);
  309. }
  310. return {
  311. tokens: usageTokens + trailingTokens,
  312. usageTokens,
  313. trailingTokens,
  314. lastUsageIndex: info.index,
  315. };
  316. }
  317. }
  318. /**
  319. * Default factory — single shared {@link BpeTokenEstimator} instance reusing
  320. * the module-loaded token counter.
  321. */
  322. let defaultInstance: BpeTokenEstimator | undefined;
  323. export function createDefaultTokenEstimator(): TokenEstimator {
  324. defaultInstance ??= new BpeTokenEstimator();
  325. return defaultInstance;
  326. }
  327. export function createDefaultContextTokenEstimator(): TokenEstimator {
  328. return createDefaultTokenEstimator();
  329. }