Field notes
2026-05-11 — context budget tracking
- Per-session context-window usage tracking shipped. New pure module
src/agent/token-budget.tsrecordsusage+modelUsagefrom each SDKresultmessage and exposes a snapshot {input/output/cache tokens, totalInput, contextWindow, pctUsed, remaining}.contextWindowis sourced frommodelUsage[*].contextWindow(SDK ships the model's advertised cap — no hardcoded table needed; max across entries when multiple models are seen in one result, e.g. subagent w/ a different model). Fallback 200k when modelUsage is empty. - Threshold helper
evaluateThreshold(sessionId, warnPct, criticalPct)is edge-triggered: each level fires exactly once per session per state, resets only onforget(). Env:SLAUDE_TOKEN_WARN_PCT(default 0.8),SLAUDE_TOKEN_CRITICAL_PCT(default 0.92, set to 0 to disable critical tier). Out-of-range values fall back to defaults. - AgentManager owns the
TokenBudget. On everyresultmessage: record → emittokenUsageevent w/ snapshot → evaluate threshold → emittokenWarningevent (levelwarn|critical) if crossed.getTokenSnapshot(sessionId)accessor exposed for MCP tools / external probes.forget(sessionId)runs in the session-teardownfinallyso a re-booted session re-fires thresholds. - SDK
PreCompacthook wired throughoptions.hooks.PreCompact: [{ hooks: [preCompact] }]. Callback emitscompactingevent withtrigger: 'manual' | 'auto'. Slack adapter sets the Assistant thread status to "compacting context…" so the user knows there's a pause. - New in-process MCP server
slaude_session(src/agent/session-mcp.ts). Single tooltoken_budgetreturns the snapshot as JSON (input/output/cache/total/window/remaining/pct + apercent_used_humanstring). Mounted via the existingMcpResolveralongsideslaude_slack/slaude_skills/ external mcp.json servers. Permission gate auto-allowsmcp__slaude_session__*(pure read). - Slack adapter listens for
tokenWarning→ posts a one-shot in-thread notice (warning / critical headline + pct + used/cap + suggestion to/abortor summarize-and-reset). Listens forcompacting→ flips status text. - Soul baseline gained a
## Context budgetsection: instructs the persona to calltoken_budgetwhen context feels long, NOT every turn; explains the 80%/92% threshold post + that SDK auto-compacts internally before the cap. - Landmine: SDK
ModelUsage.contextWindowis the SOURCE OF TRUTH for the model's cap. Don't hardcode 200k / 1M tables — they go stale when Anthropic ships new tiers. Subagents w/ different models surface in the samemodelUsagemap → take the max so the warning fires at the right percentage of the live session's window, not a smaller subagent's. - TDD: 16 tests for
TokenBudget, 4 forsessionHandlers, 2 new for env getters. Total suite 211 pass / 392 assertions / 96.66% func / 99.63% line — still above the 0.97 line / 0.80 func threshold.