算法艺术创作
algorithmic-art
通过代码和可调参数创作生成艺术与交互式视觉效果。
manage-token-budget【设计与创意】Monitor, cap, and recover from context accumulation in agentic systems. Covers per-cycle cost tracking, context window auditing, budget caps with enforcement policies, emergency pruning when approaching limits, and progressive disclosure integration to minimize token spend on routing. Use when running long-lived agent loops (heartbeats, polling, auto…
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
Control cost + context footprint of agentic systems. Track tokens per cycle, audit what consumes context, enforce budget caps, prune low-value context under pressure, route through metadata before loading full procedures. Core principle: every token in context window must earn its place. Tokens informing decisions stay; tokens occupying space without influencing output get pruned.
Community evidence: 37-hour autonomous session cost $13.74 from 30-minute heartbeat interval combined with verbose system instructions + unchecked context accumulation. Fix: rewrote heartbeat to 4-hour intervals, switched to notification-only mode, eliminated feed browsing from loop. This skill codifies patterns preventing such incidents.
Instrument agent loop to log token usage at every execution boundary.
For each cycle (heartbeat, poll, task), capture:
Store these in structured log (JSON lines, CSV, database) — not in context window itself:
{"cycle": 47, "ts": "2026-03-12T14:30:00Z", "trigger": "heartbeat",
"input_tokens": 18420, "output_tokens": 2105, "cost_usd": 0.0891,
"cumulative_cost_usd": 3.42}
If system has no instrumentation, estimate from API billing:
Got: Log shows per-cycle token counts + costs, with granularity to identify expensive cycles + why. Log lives outside context window.
If fail: Exact token counts unavailable (some APIs do not return usage metadata)? Use billing dashboard for averages. Even coarse tracking (daily cost / daily cycle count) reveals trends. No tracking possible? Go to Step 2, work from context audit — estimate costs from context size.
Measure what occupies context window, rank consumers by size.
Decompose context into components, measure each:
Produce context budget table:
Context Budget Audit:
+------------------------+--------+------+-----------------------------------+
| Component | Tokens | % | Notes |
+------------------------+--------+------+-----------------------------------+
| System prompt | 4,200 | 21% | Includes CLAUDE.md chain |
| Memory (auto-loaded) | 3,800 | 19% | MEMORY.md + 4 topic files |
| Tool schemas | 2,600 | 13% | 3 MCP servers, 47 tools |
| Active skill procedure | 1,900 | 9% | Full SKILL.md loaded |
| Conversation history | 5,100 | 25% | 12 prior turns |
| Current cycle content | 2,400 | 12% | Tool outputs from this cycle |
+------------------------+--------+------+-----------------------------------+
| TOTAL | 20,000 | 100% | Model limit: 200,000 |
| Remaining headroom |180,000 | | |
+------------------------+--------+------+-----------------------------------+
Flag components disproportionately large vs decision-making value. 4,000-token memory file current task never references is pure overhead.
Got: Ranked table shows each context consumer, size, percent of window. At least one component stands out as candidate for reduction — most often conversation history or verbose tool outputs.
If fail: Exact token counts per component hard to get? Use character count / 4 as rough approximation for English. For structured data (JSON, YAML), character count / 3. Goal is relative ranking, not exact measurement.
Define hard + soft limits, specify what happens when each reached.
Soft limit (warning threshold): typically 60-75% of hard limit. When hit:
Hard limit (stop threshold): absolute max spend or context size. When hit:
Per-cycle cap: max tokens or cost for any single cycle. Prevents single runaway cycle from consuming whole budget:
Document caps in workflow config:
token_budget:
soft_limit_usd: 5.00 # warn and begin pruning
hard_limit_usd: 10.00 # halt and alert
per_cycle_cap_usd: 0.50 # max per individual cycle
soft_limit_pct: 70 # % of context window triggering pruning
hard_limit_pct: 90 # % of context window triggering halt
enforcement: strict # strict = halt on hard limit; advisory = log only
alert_channel: notification # how to notify the operator
Got: Documented budget caps at three levels (soft, hard, per-cycle) with explicit enforcement actions. Policy answers "what happens when we hit the limit?" before limit hit.
If fail: Setting precise dollar limits premature (new workflow, unknown cost profile)? Start with context-percentage limits only (soft 70%, hard 90%), add dollar limits after 24-48 hours of cost tracking. Advisory mode (log not halt) acceptable during calibration.
When approaching limits, drop low-value context to stay within budget.
Pruning priority order (drop lowest-value first):
For each pruned item, preserve one-line tombstone:
[PRUNED: 2,400 tokens of npm audit output from cycle 12 — 3 vulnerabilities found, all patched]
Tombstone costs ~20 tokens but preserves decision-relevant conclusion.
Got: Context window usage drops below soft limit after pruning. Each pruned item has tombstone preserving conclusion. No decision-critical info lost — only evidence behind already-made decisions.
If fail: Pruning to priority level 4 still leaves usage above soft limit? Workflow fundamentally too context-heavy for current cycle frequency. Escalate to human: "Context usage at N% after pruning. Options: (a) increase cycle interval, (b) reduce scope per cycle, (c) split into sub-workflows, (d) accept higher cost."
Route through registry metadata before loading full skill procedures — spend tokens on routing, not on reading.
Pattern:
_registry.yml — roughly 3-5 lines, ~50 tokensApply same pattern to other large context payloads:
Without progressive disclosure:
Load 5 candidate skills → 5 × 1,500 tokens = 7,500 tokens → use 1 skill
With progressive disclosure:
Route through 5 registry entries → 5 × 50 tokens = 250 tokens
Load 1 matched skill → 1 × 1,500 tokens = 1,500 tokens
Total: 1,750 tokens (77% reduction)
Got: Skill loading follows two-phase pattern: lightweight routing via metadata, then full loading only on confirmed match. Same pattern applied to memory, tool schemas, file contents where applicable.
If fail: Registry metadata insufficient for routing (descriptions too vague, tags missing)? Improve registry entries rather than abandoning progressive disclosure. Fix is better metadata, not more context loading.
Set execution intervals based on cost data, not arbitrary schedules.
Calculate cost-per-hour at current cycle interval:
cost_per_hour = avg_cost_per_cycle × cycles_per_hourCompare against budget:
hours_until_hard_limit = (hard_limit - cumulative_cost) / cost_per_hourDetermine minimum effective interval:
Apply interval:
Before: 30-minute heartbeat, verbose processing
→ 48 cycles/day × $0.09/cycle = $4.32/day
After: 4-hour heartbeat, notification-only
→ 6 cycles/day × $0.04/cycle = $0.24/day
→ 94% cost reduction
Got: Cycle interval justified by cost data, matches monitored system refresh rate. Interval-cost tradeoff documented so future adjustments have baseline.
If fail: System requires low-latency response, cannot tolerate longer intervals? Reduce per-cycle cost instead (smaller system prompts, fewer tool schemas loaded, summarized history). Budget equation has two levers: frequency + cost-per-cycle.
Confirm all controls working, system operates within budget.
Budget Validation Report:
+-----------------------+----------+--------+
| Check | Expected | Actual |
+-----------------------+----------+--------+
| Per-cycle logging | Present | |
| Soft limit warning | Fires | |
| Hard limit halt | Halts | |
| Per-cycle cap | Truncates| |
| Progressive disclosure| Routes | |
| Daily cost projection | < $X.XX | |
+-----------------------+----------+--------+
Got: All five controls (tracking, soft limit, hard limit, per-cycle cap, progressive disclosure) verified working. Cost projection within intended budget.
If fail: Controls not firing? Check enforcement mechanism wired into actual execution loop, not just documented. Configuration without enforcement is plan, not control. Cost projection exceeds budget? Return to Step 6, adjust cycle interval or per-cycle cost.
assess-context — evaluate reasoning context for structural health; complements context window audit in Step 2metal — extract conceptual essence from codebases; progressive disclosure pattern applies to metal's prospect phasechrysopoeia — value extraction + dead weight elimination; applies same value-per-token thinking at code levelmanage-memory — organize + prune persistent memory files; directly reduces memory component of context budgets