Skip to content

Phase 1: Cost tracking with budget enforcement for ADF agents #638

@AlexMikhalev

Description

@AlexMikhalev

Parent Epic

#637

Summary

Add per-agent cost tracking by parsing Claude Code's --output-format stream-json output and enforcing configurable budget limits.

Changes Required

terraphim_spawner

  • Add --output-format stream-json to Claude CLI args in config.rs:infer_args()
  • Create cost.rs module with CostEvent struct and stream JSON parser
  • Parse stdout for Claude stream JSON events: session_id, usage.input_tokens, usage.output_tokens, cost_usd
  • Emit CostEvent via broadcast channel alongside OutputEvent

terraphim_orchestrator

  • Add budget_monthly_cents: Option<u64> field to AgentDefinition (with #[serde(default)])
  • Add CostTracker struct: accumulates per-agent spend, writes to costs.jsonl
  • Budget enforcement in reconcile_tick(): warn at 80%, pause agent at 100%
  • New AgentStatus field: spent_monthly_cents

Config

[[agents]]
name = "product-development"
budget_monthly_cents = 5000  # $50/month limit

Reference

  • Paperclip cost service: server/src/services/costs.ts
  • Paperclip Claude parser: packages/adapters/claude-local/src/server/parse.ts
  • Claude stream JSON schema: {type: "result", usage: {input_tokens, output_tokens}, cost_usd}

Acceptance Criteria

  • Claude agents emit cost events from stream JSON output
  • Per-agent costs accumulated and written to costs.jsonl
  • Budget enforcement pauses agent when limit reached
  • Codex agents gracefully skip cost tracking (no stream JSON available)
  • Existing agents work without budget_monthly_cents (default: no limit)
  • Unit tests for stream JSON parser and budget enforcement

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions