agengo 0.3.0

Orchestrate AI coding agents (Claude Code) to build, verify, review and integrate tasks in isolated Git worktrees
//! Provider-neutral token and cost accounting for agent attempts.
//!
//! Every attempt may report usage with these optional fields:
//! `input_tokens`, `output_tokens`, `cache_read_tokens`, `cache_write_tokens`
//! (non-negative integers), `cost_usd` (non-negative number) and `model`
//! (string). Claude Code's JSON output is mapped automatically; a custom
//! adapter adds a top-level `usage` object with the same field names.
//!
//! Usage is telemetry: a malformed field is dropped, never an error, so it
//! cannot fail a run. agengo never estimates prices itself.

use serde_json::{json, Map, Value};

pub const TOKEN_FIELDS: [&str; 4] = [
    "input_tokens",
    "output_tokens",
    "cache_read_tokens",
    "cache_write_tokens",
];

fn count(value: &Value) -> Option<Value> {
    value.as_u64().map(Value::from)
}

fn money(value: &Value) -> Option<Value> {
    value
        .as_f64()
        .filter(|amount| amount.is_finite() && *amount >= 0.0)
        .map(Value::from)
}

fn finish(usage: Map<String, Value>) -> Option<Value> {
    (!usage.is_empty()).then_some(Value::Object(usage))
}

/// Usage reported by a custom adapter in its reply's `usage` object.
pub fn from_adapter(raw: &Value) -> Option<Value> {
    let raw = raw.as_object()?;
    let mut usage = Map::new();
    for field in TOKEN_FIELDS {
        if let Some(value) = raw.get(field).and_then(count) {
            usage.insert(field.into(), value);
        }
    }
    if let Some(cost) = raw.get("cost_usd").and_then(money) {
        usage.insert("cost_usd".into(), cost);
    }
    if let Some(model) = raw
        .get("model")
        .and_then(Value::as_str)
        .filter(|name| !name.trim().is_empty())
    {
        usage.insert("model".into(), json!(model));
    }
    finish(usage)
}

/// Usage in the envelope that `claude -p --output-format json` prints.
pub fn from_claude(envelope: &Value) -> Option<Value> {
    let raw = &envelope["usage"];
    let mut usage = Map::new();
    for (theirs, ours) in [
        ("input_tokens", "input_tokens"),
        ("output_tokens", "output_tokens"),
        ("cache_read_input_tokens", "cache_read_tokens"),
        ("cache_creation_input_tokens", "cache_write_tokens"),
    ] {
        if let Some(value) = count(&raw[theirs]) {
            usage.insert(ours.into(), value);
        }
    }
    if let Some(cost) = money(&envelope["total_cost_usd"]) {
        usage.insert("cost_usd".into(), cost);
    }
    if let Some(models) = envelope["modelUsage"].as_object() {
        let names: Vec<_> = models.keys().map(String::as_str).collect();
        if !names.is_empty() {
            usage.insert("model".into(), json!(names.join(",")));
        }
    }
    finish(usage)
}

/// One-line human summary, or `None` when nothing was reported.
pub fn describe(usage: &Value) -> Option<String> {
    let mut parts = Vec::new();
    for (field, label) in [
        ("input_tokens", "in"),
        ("output_tokens", "out"),
        ("cache_read_tokens", "cache read"),
        ("cache_write_tokens", "cache write"),
    ] {
        if let Some(value) = usage[field].as_u64() {
            parts.push(format!("{label} {value}"));
        }
    }
    let mut text = if parts.is_empty() {
        String::new()
    } else {
        format!("tokens {}", parts.join(", "))
    };
    if let Some(cost) = usage["cost_usd"].as_f64() {
        if !text.is_empty() {
            text.push_str(" · ");
        }
        text.push_str(&format!("${cost:.4}"));
    }
    (!text.is_empty()).then_some(text)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn claude_envelope_maps_to_neutral_fields() {
        let envelope = json!({
            "total_cost_usd": 0.0204,
            "usage": {"input_tokens": 2, "output_tokens": 14,
                "cache_read_input_tokens": 1670, "cache_creation_input_tokens": 2476,
                "server_tool_use": {"web_search_requests": 0}},
            "modelUsage": {"claude-x": {}}
        });
        assert_eq!(
            from_claude(&envelope),
            Some(
                json!({"input_tokens":2,"output_tokens":14,"cache_read_tokens":1670,
                "cache_write_tokens":2476,"cost_usd":0.0204,"model":"claude-x"})
            )
        );
        assert_eq!(from_claude(&json!({"result":"x"})), None);
    }

    #[test]
    fn adapter_usage_keeps_valid_fields_and_drops_the_rest() {
        let raw = json!({"input_tokens": 10, "output_tokens": -3, "cost_usd": "free",
            "cache_read_tokens": 1.5, "model": "gpt-x", "extra": 1});
        assert_eq!(
            from_adapter(&raw),
            Some(json!({"input_tokens":10,"model":"gpt-x"}))
        );
        assert_eq!(from_adapter(&json!({"output_tokens": -1})), None);
        assert_eq!(from_adapter(&json!("lots")), None);
    }

    #[test]
    fn description_lists_only_reported_values() {
        assert_eq!(
            describe(&json!({"input_tokens":10,"output_tokens":5,"cost_usd":0.5})).as_deref(),
            Some("tokens in 10, out 5 · $0.5000")
        );
        assert_eq!(describe(&json!({"model":"m"})), None);
    }
}