token-estimator.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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 { createHash } from 'node:crypto';
  50. import { countTokens as countO200kBase } from 'gpt-tokenizer/model/gpt-4o';
  51. import type { ContextCompactionSummaryMessage } from './types.js';
  52. export interface ContextTokenEstimate {
  53. /** Estimated total tokens consumed by `messages`. */
  54. tokens: number;
  55. /**
  56. * Provider-reported usage at the last successful assistant message — the
  57. * ground-truth portion of `tokens`. `0` when no assistant usage was found.
  58. */
  59. usageTokens: number;
  60. /**
  61. * Estimator-computed token count for messages after `lastUsageIndex`. When
  62. * `lastUsageIndex` is `null`, this equals `tokens` (full estimate).
  63. */
  64. trailingTokens: number;
  65. /** Index of the assistant message whose usage block was used, or `null`. */
  66. lastUsageIndex: number | null;
  67. }
  68. export interface TokenEstimator {
  69. /** Estimate tokens for raw text without message structural overhead. */
  70. estimateTextTokens(text: string): number;
  71. /** Return the shared stand-in used for one model-visible image/video block. */
  72. estimateVisualTokens(): number;
  73. /** Estimate tokens for a single message. */
  74. estimateMessage(message: AgentMessage): number;
  75. /** Estimate tokens for an arbitrary sequence of messages (no ground truth). */
  76. estimateMessages(messages: AgentMessage[]): number;
  77. /**
  78. * Estimate context tokens for a transcript, preferring provider usage as the
  79. * prefix ground-truth. Mirrors pi-agent-core's `estimateContextTokens`
  80. * contract so existing call sites can swap implementations without changing
  81. * downstream interpretation.
  82. */
  83. estimateContextTokens(messages: AgentMessage[]): ContextTokenEstimate;
  84. }
  85. /** Per-message structural overhead (role wrapper + delimiters). */
  86. const MESSAGE_STRUCTURAL_OVERHEAD = 4;
  87. /** Stand-in token count for an image or legacy/raw video block. */
  88. const VISUAL_TOKEN_STAND_IN = 4_800;
  89. /** Pluggable encoder seam — tests inject deterministic encoders. */
  90. export type EncodeFn = (text: string) => number[] | Uint32Array;
  91. const MAX_EXACT_TOKENIZER_CHARS = 4_096;
  92. const UNICODE_LETTER_OR_NUMBER = /[\p{L}\p{N}]/u;
  93. function hasOversizedAlphanumericRun(text: string): boolean {
  94. let runLength = 0;
  95. for (const character of text) {
  96. const codePoint = character.codePointAt(0) ?? 0;
  97. const isLetterOrNumber =
  98. codePoint <= 0x7f
  99. ? (codePoint >= 0x30 && codePoint <= 0x39) ||
  100. (codePoint >= 0x41 && codePoint <= 0x5a) ||
  101. (codePoint >= 0x61 && codePoint <= 0x7a)
  102. : UNICODE_LETTER_OR_NUMBER.test(character);
  103. if (!isLetterOrNumber) {
  104. runLength = 0;
  105. continue;
  106. }
  107. runLength += 1;
  108. if (runLength > MAX_EXACT_TOKENIZER_CHARS) return true;
  109. }
  110. return false;
  111. }
  112. function estimateTextTokensUpperBound(text: string): number {
  113. return Buffer.byteLength(text, 'utf8');
  114. }
  115. function safeJsonStringify(value: unknown): string {
  116. try {
  117. return JSON.stringify(value) ?? 'undefined';
  118. } catch {
  119. return '[unserializable]';
  120. }
  121. }
  122. function isVisualContentBlock(block: { type?: unknown }): boolean {
  123. return block.type === 'image' || block.type === 'video';
  124. }
  125. function calculateContextTokens(usage: {
  126. input: number;
  127. output: number;
  128. cacheRead: number;
  129. cacheWrite: number;
  130. totalTokens: number;
  131. }): number {
  132. return usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
  133. }
  134. interface AssistantUsageRef {
  135. input: number;
  136. output: number;
  137. cacheRead: number;
  138. cacheWrite: number;
  139. totalTokens: number;
  140. }
  141. function getAssistantUsage(message: AgentMessage): AssistantUsageRef | undefined {
  142. if (message.role !== 'assistant') return undefined;
  143. const m = message as AgentMessage & {
  144. usage?: AssistantUsageRef;
  145. stopReason?: string;
  146. };
  147. if (m.stopReason === 'aborted' || m.stopReason === 'error') return undefined;
  148. return m.usage;
  149. }
  150. function getLastAssistantUsageInfo(
  151. messages: AgentMessage[],
  152. ): { usage: AssistantUsageRef; index: number } | undefined {
  153. let firstFreshIndex = 0;
  154. let compactedAt: number | undefined;
  155. for (let i = messages.length - 1; i >= 0; i -= 1) {
  156. if (messages[i]!.role !== 'compactionSummary') continue;
  157. const summary = messages[i] as ContextCompactionSummaryMessage;
  158. const keptCount = summary.keptMessageCount;
  159. if (keptCount !== undefined) {
  160. // Kept assistants appear AFTER the summary too. Only appended responses
  161. // describe the replacement context; their wall-clock timestamps may tie
  162. // or precede the summary if the clock changed.
  163. if (!Number.isSafeInteger(keptCount) || keptCount < 0) return undefined;
  164. firstFreshIndex = i + 1 + keptCount;
  165. } else {
  166. // Legacy persisted transcripts have no explicit retained-tail boundary.
  167. // Match the local runtime's conservative timestamp freshness rule.
  168. if (!Number.isFinite(summary.timestamp)) return undefined;
  169. compactedAt = summary.timestamp;
  170. firstFreshIndex = i + 1;
  171. }
  172. break;
  173. }
  174. for (let i = messages.length - 1; i >= firstFreshIndex; i -= 1) {
  175. const message = messages[i]!;
  176. if (
  177. compactedAt !== undefined &&
  178. (!Number.isFinite(message.timestamp) || message.timestamp <= compactedAt)
  179. ) {
  180. continue;
  181. }
  182. const usage = getAssistantUsage(message);
  183. if (usage) return { usage, index: i };
  184. }
  185. return undefined;
  186. }
  187. const MAX_INLINE_CACHE_KEY_UNITS = 256;
  188. const MAX_CACHED_TEXT_ENTRIES = 2_048;
  189. export class BpeTokenEstimator implements TokenEstimator {
  190. private readonly countExactTokens: (text: string) => number;
  191. // Bounded content keys survive detached histories without retaining long
  192. // message bodies. Hash UTF-16 units so lone surrogates stay distinct.
  193. private readonly textTokens = new Map<string, number>();
  194. /**
  195. * @param encoder Override the default o200k_base tokenizer. Tests inject
  196. * deterministic encoders (e.g. `text => text.split(' ')`); production passes
  197. * no argument so the default GPT-4o BPE token counter is used.
  198. *
  199. * The default wraps gpt-tokenizer with `allowedSpecial: 'all'`. Without it,
  200. * gpt-tokenizer defaults to `disallowedSpecial: 'all'` and THROWS on any
  201. * special-token literal (e.g. `<|endoftext|>`) appearing in transcript text.
  202. * Since this estimator runs inside the fail-closed `beforeLlmCall` checkpoint,
  203. * such a throw would abort the whole turn. We only count tokens, so treating
  204. * special-token literals as ordinary text is correct here.
  205. */
  206. constructor(encoder?: EncodeFn) {
  207. this.countExactTokens = encoder
  208. ? (text) => encoder(text).length
  209. : (text) => countO200kBase(text, { allowedSpecial: 'all' });
  210. }
  211. estimateTextTokens(text: string): number {
  212. if (!text) return 0;
  213. const key =
  214. text.length <= MAX_INLINE_CACHE_KEY_UNITS
  215. ? `text:${text}`
  216. : `sha256:${createHash('sha256').update(text, 'utf16le').digest('hex')}`;
  217. const cached = this.textTokens.get(key);
  218. if (cached !== undefined) {
  219. this.textTokens.delete(key);
  220. this.textTokens.set(key, cached);
  221. return cached;
  222. }
  223. try {
  224. if (text.length > MAX_EXACT_TOKENIZER_CHARS && hasOversizedAlphanumericRun(text)) {
  225. return estimateTextTokensUpperBound(text);
  226. }
  227. const tokens = this.countExactTokens(text);
  228. if (!Number.isFinite(tokens) || tokens < 0) return estimateTextTokensUpperBound(text);
  229. if (this.textTokens.size >= MAX_CACHED_TEXT_ENTRIES) {
  230. const oldest = this.textTokens.keys().next().value;
  231. if (oldest !== undefined) this.textTokens.delete(oldest);
  232. }
  233. this.textTokens.set(key, tokens);
  234. return tokens;
  235. } catch {
  236. return estimateTextTokensUpperBound(text);
  237. }
  238. }
  239. estimateVisualTokens(): number {
  240. return VISUAL_TOKEN_STAND_IN;
  241. }
  242. estimateMessage(message: AgentMessage): number {
  243. let tokens = MESSAGE_STRUCTURAL_OVERHEAD;
  244. switch (message.role) {
  245. case 'user': {
  246. const content = (message as Extract<AgentMessage, { role: 'user' }>).content;
  247. if (typeof content === 'string') {
  248. tokens += this.estimateTextTokens(content);
  249. } else if (Array.isArray(content)) {
  250. for (const block of content) {
  251. if (block.type === 'text' && block.text) {
  252. tokens += this.estimateTextTokens(block.text);
  253. } else if (isVisualContentBlock(block)) {
  254. tokens += this.estimateVisualTokens();
  255. }
  256. }
  257. }
  258. return tokens;
  259. }
  260. case 'assistant': {
  261. const assistant = message as Extract<AgentMessage, { role: 'assistant' }>;
  262. for (const block of assistant.content) {
  263. if (block.type === 'text') {
  264. tokens += this.estimateTextTokens(block.text);
  265. } else if (block.type === 'thinking') {
  266. tokens += this.estimateTextTokens((block as { thinking: string }).thinking);
  267. } else if (block.type === 'toolCall') {
  268. tokens += this.estimateTextTokens(block.name);
  269. tokens += this.estimateTextTokens(safeJsonStringify(block.arguments));
  270. }
  271. }
  272. return tokens;
  273. }
  274. case 'toolResult':
  275. case 'custom': {
  276. const content = (
  277. message as Extract<AgentMessage, { role: 'toolResult' | 'custom' }> & {
  278. content: string | Array<{ type: string; text?: string }>;
  279. }
  280. ).content;
  281. if (typeof content === 'string') {
  282. tokens += this.estimateTextTokens(content);
  283. } else if (Array.isArray(content)) {
  284. for (const block of content) {
  285. if (block.type === 'text' && typeof block.text === 'string') {
  286. tokens += this.estimateTextTokens(block.text);
  287. } else if (isVisualContentBlock(block)) {
  288. tokens += this.estimateVisualTokens();
  289. }
  290. }
  291. }
  292. return tokens;
  293. }
  294. case 'bashExecution': {
  295. const m = message as AgentMessage & {
  296. command?: string;
  297. output?: string;
  298. };
  299. tokens += this.estimateTextTokens(m.command ?? '');
  300. tokens += this.estimateTextTokens(m.output ?? '');
  301. return tokens;
  302. }
  303. case 'branchSummary':
  304. case 'compactionSummary': {
  305. const m = message as AgentMessage & { summary?: string };
  306. tokens += this.estimateTextTokens(m.summary ?? '');
  307. return tokens;
  308. }
  309. }
  310. return tokens;
  311. }
  312. estimateMessages(messages: AgentMessage[]): number {
  313. let total = 0;
  314. for (const message of messages) {
  315. total += this.estimateMessage(message);
  316. }
  317. return total;
  318. }
  319. estimateContextTokens(messages: AgentMessage[]): ContextTokenEstimate {
  320. const info = getLastAssistantUsageInfo(messages);
  321. if (!info) {
  322. const trailing = this.estimateMessages(messages);
  323. return {
  324. tokens: trailing,
  325. usageTokens: 0,
  326. trailingTokens: trailing,
  327. lastUsageIndex: null,
  328. };
  329. }
  330. const usageTokens = calculateContextTokens(info.usage);
  331. let trailingTokens = 0;
  332. for (let i = info.index + 1; i < messages.length; i += 1) {
  333. trailingTokens += this.estimateMessage(messages[i]!);
  334. }
  335. return {
  336. tokens: usageTokens + trailingTokens,
  337. usageTokens,
  338. trailingTokens,
  339. lastUsageIndex: info.index,
  340. };
  341. }
  342. }
  343. /**
  344. * Default factory — single shared {@link BpeTokenEstimator} instance reusing
  345. * the module-loaded token counter.
  346. */
  347. let defaultInstance: BpeTokenEstimator | undefined;
  348. export function createDefaultTokenEstimator(): TokenEstimator {
  349. defaultInstance ??= new BpeTokenEstimator();
  350. return defaultInstance;
  351. }
  352. export function createDefaultContextTokenEstimator(): TokenEstimator {
  353. return createDefaultTokenEstimator();
  354. }