/** * TokenEconomics — Cognitive Overload Detection * * **Evolution 3: Token Economics** * * Profiles the token density and context spread of MCP tool * responses to detect cognitive overload scenarios where the * LLM's working memory is flooded by verbose tool output, * evicting system rules and degrading reasoning quality. * * **Key insight**: An MCP tool that returns 50KB of JSON per * call will rapidly exhaust the context window. If that output * isn't constrained by `agentLimit` or `egressMaxBytes`, the * system rules injected by the Presenter's `addRules()` will * be pushed out of the LLM's attention window — silently * degrading behavioral correctness. * * This module provides: * * 1. **Static analysis**: Estimate token density from Presenter * schema and guardrail configuration (zero-cost at runtime). * * 2. **Runtime profiling**: Measure actual token counts of * response blocks after Presenter rendering (opt-in). * * 3. **Overload classification**: Classify responses into * risk levels based on configurable thresholds. * * 4. **Integration with BehaviorDigest**: Token economics risk * level is part of the behavioral contract — changes to * the token profile are tracked as contract deltas. * * Pure-function module for analysis; runtime profiling hooks * are designed for zero-overhead when not configured. * * @module */ /** * Token economics analysis for a single tool response. */ export interface TokenAnalysis { /** Tool name */ readonly toolName: string; /** Action key, if applicable */ readonly actionKey: string | null; /** Estimated total tokens in the response */ readonly estimatedTokens: number; /** Number of content blocks in the response */ readonly blockCount: number; /** Per-block token breakdown */ readonly blocks: readonly BlockTokenProfile[]; /** Overhead tokens (rules, affordances, UI decorators) */ readonly overheadTokens: number; /** Data payload tokens (actual tool output) */ readonly dataTokens: number; /** Overhead-to-data ratio (higher = more overhead) */ readonly overheadRatio: number; /** Risk classification */ readonly risk: TokenRisk; /** Human-readable advisory */ readonly advisory: string | null; } /** * Token profile for a single content block. */ export interface BlockTokenProfile { /** Block type (e.g., 'text', 'resource', 'image') */ readonly type: string; /** Estimated tokens in this block */ readonly estimatedTokens: number; /** Raw byte size */ readonly bytes: number; } /** * Token risk classification. */ export type TokenRisk = 'low' | 'medium' | 'high' | 'critical'; /** * Thresholds for token risk classification. */ export interface TokenThresholds { /** Maximum tokens for 'low' risk (default: 1000) */ readonly low: number; /** Maximum tokens for 'medium' risk (default: 4000) */ readonly medium: number; /** Maximum tokens for 'high' risk (default: 8000) */ readonly high: number; } /** * Configuration for the token economics profiler. */ export interface TokenEconomicsConfig { /** Custom thresholds (defaults provided) */ readonly thresholds?: Partial; /** Whether to emit warnings to debug observer */ readonly emitWarnings?: boolean; /** Maximum acceptable overhead ratio (default: 0.3) */ readonly maxOverheadRatio?: number; } /** * Static token profile derived from Presenter configuration. * Computed once at build time — zero runtime cost. */ export interface StaticTokenProfile { /** Tool name */ readonly toolName: string; /** Estimated minimum tokens per response */ readonly minTokens: number; /** Estimated maximum tokens per response (with agentLimit) */ readonly maxTokens: number; /** Whether the maximum is bounded (agentLimit/egressMaxBytes set) */ readonly bounded: boolean; /** Per-field estimated token cost */ readonly fieldBreakdown: readonly FieldTokenEstimate[]; /** Risk classification based on max estimate */ readonly risk: TokenRisk; /** Recommendations for reducing token cost */ readonly recommendations: readonly string[]; } /** * Per-field token estimate. */ export interface FieldTokenEstimate { /** Field name */ readonly name: string; /** Estimated tokens per occurrence */ readonly estimatedTokens: number; /** Whether this field is a collection/array type */ readonly isCollection: boolean; } /** * Estimate token count from a string using the ~4 chars/token heuristic. * * This is a fast approximation suitable for profiling. For precise * token counting, use a tokenizer library (tiktoken, etc.). * * @param text - The text to estimate tokens for * @returns Estimated token count */ export declare function estimateTokens(text: string): number; /** * Estimate tokens for a content block structure (MCP response block). * * @param block - The content block with `type` and `text` fields * @returns Block-level token profile */ export declare function profileBlock(block: { type: string; text?: string; }): BlockTokenProfile; /** * Profile a complete tool response for token economics. * * Analyzes all content blocks in a tool response to compute * total token usage, overhead ratio, and risk classification. * * @param toolName - Name of the tool that produced the response * @param actionKey - Action key (if applicable) * @param blocks - Content blocks from the tool response * @param overheadBlocks - Number of blocks that are overhead (rules, UI) * @param config - Token economics configuration * @returns Complete token analysis */ export declare function profileResponse(toolName: string, actionKey: string | null, blocks: readonly { type: string; text?: string; }[], overheadBlocks?: number, config?: TokenEconomicsConfig): TokenAnalysis; /** * Compute a static token profile from Presenter metadata. * * This runs once at manifest compilation time and produces * a zero-cost profile that estimates the worst-case token * usage for a tool based on its schema and guardrail config. * * @param toolName - Tool name * @param schemaKeys - Presenter schema field names * @param agentLimitMax - Maximum items from agentLimit() config * @param egressMaxBytes - Maximum bytes from egressMaxBytes() config * @returns Static token profile with recommendations */ export declare function computeStaticProfile(toolName: string, schemaKeys: readonly string[], agentLimitMax: number | null, egressMaxBytes: number | null): StaticTokenProfile; /** * Aggregate static profiles into a server-level summary. * * @param profiles - All static profiles for the server * @returns Server-level token economics summary */ export declare function aggregateProfiles(profiles: readonly StaticTokenProfile[]): ServerTokenSummary; /** * Server-level token economics summary. */ export interface ServerTokenSummary { /** Total number of tools */ readonly toolCount: number; /** Sum of all tools' minimum token estimates */ readonly totalMinTokens: number; /** Sum of all tools' maximum token estimates */ readonly totalMaxTokens: number; /** Number of tools without bounded output */ readonly unboundedToolCount: number; /** Names of unbounded tools */ readonly unboundedToolNames: readonly string[]; /** Overall risk classification */ readonly overallRisk: TokenRisk; /** Names of critical-risk tools */ readonly criticalToolNames: readonly string[]; /** Aggregated recommendations */ readonly recommendations: readonly string[]; } //# sourceMappingURL=TokenEconomics.d.ts.map