slaude Docs

Field notes

2026-05-11 — context budget tracking

  • Per-session context-window usage tracking shipped. New pure module src/agent/token-budget.ts records usage + modelUsage from each SDK result message and exposes a snapshot {input/output/cache tokens, totalInput, contextWindow, pctUsed, remaining}. contextWindow is sourced from modelUsage[*].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 on forget(). 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 every result message: record → emit tokenUsage event w/ snapshot → evaluate threshold → emit tokenWarning event (level warn | critical) if crossed. getTokenSnapshot(sessionId) accessor exposed for MCP tools / external probes. forget(sessionId) runs in the session-teardown finally so a re-booted session re-fires thresholds.
  • SDK PreCompact hook wired through options.hooks.PreCompact: [{ hooks: [preCompact] }]. Callback emits compacting event with trigger: '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 tool token_budget returns the snapshot as JSON (input/output/cache/total/window/remaining/pct + a percent_used_human string). Mounted via the existing McpResolver alongside slaude_slack / slaude_skills / external mcp.json servers. Permission gate auto-allows mcp__slaude_session__* (pure read).
  • Slack adapter listens for tokenWarning → posts a one-shot in-thread notice (warning / critical headline + pct + used/cap + suggestion to /abort or summarize-and-reset). Listens for compacting → flips status text.
  • Soul baseline gained a ## Context budget section: instructs the persona to call token_budget when context feels long, NOT every turn; explains the 80%/92% threshold post + that SDK auto-compacts internally before the cap.
  • Landmine: SDK ModelUsage.contextWindow is 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 same modelUsage map → 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 for sessionHandlers, 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.