/** * Token estimation utilities. * Uses ~4 chars per token heuristic (works well for English + code). */ export function estimateTokens(text: string): number { if (!text) return 0 return Math.ceil(text.length / 4) } export function estimateMessagesTokens( messages: Array<{ role: string; content: unknown }> ): number { let total = 0 for (const msg of messages) { const content = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content ?? "") total += estimateTokens(content) // Overhead per message (~4 tokens for role, separators) total += 4 } return total } export function estimateToolSchemaTokens(schemas: Array>): number { let total = 0 for (const schema of schemas) { total += estimateTokens(String(schema.description ?? "")) total += estimateTokens(String(schema.name ?? "")) total += estimateTokens(JSON.stringify(schema.input_schema ?? {})) } return total } export function formatTokenCount(tokens: number): string { if (tokens >= 1_000_000) return `${(tokens / 1_000_000).toFixed(1)}M` if (tokens >= 1_000) return `${(tokens / 1_000).toFixed(1)}K` return String(tokens) }