ag-agent 0.22.1

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
//! Usage accounting for Claude Code `stream-json` output.
//!
//! Claude Code reports, per its Agent SDK cost-tracking documentation:
//!
//! - the usage of each API response on its assistant messages, which share one
//!   message id when a response calls several tools, and whose `output_tokens`
//!   is a placeholder;
//! - each turn's main-loop usage on that turn's `result`, which leaves out
//!   subagents;
//! - on each `result`, `modelUsage`: per model, the tokens and `costUSD` of the
//!   whole process so far, subagents included, plus a resumed session's earlier
//!   totals on Claude Code 2.1.277 and later.
//!
//! The Messages usage shape leaves cache reads and writes out of
//! `input_tokens`; this module counts input with both included. A turn's own
//! per-model usage is the difference between its `modelUsage` totals and the
//! totals after the session's previous resumed turn, which the host keeps as
//! an opaque checkpoint. Live updates use the main-loop usage at list price;
//! the turn result switches to Claude Code's own per-model figures. A run on
//! a Claude subscription, as [`ClaudeUsageMeter::billing`] detects it,
//! carries API-equivalent costs.

use std::collections::{BTreeMap, HashMap, HashSet};
use std::ffi::OsString;
use std::path::Path;
use std::process::Command;

use ag_contracts::{
    AgentRequestKind, ContextFill, CostBasis, CostEstimate, ModelUsage, PlanLogin, TurnUsage,
    UsageCheckpoint,
};
use ag_harness::provider::ModelProvider;
use semver::Version;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::agent::usage::{Billing, list_price};

/// First Claude Code release whose resumed sessions restore their earlier
/// totals into `modelUsage`; earlier releases start each process at zero.
const CUMULATIVE_RESUME_VERSION: Version = Version::new(2, 1, 277);

/// Environment variables that send Claude Code to a bearer token or a
/// custom endpoint instead of an interactive login.
const ALTERNATE_CREDENTIAL_VARIABLES: [&str; 2] = ["ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL"];

/// Prefix of the environment switches that run Claude Code on a cloud
/// provider, such as `CLAUDE_CODE_USE_BEDROCK`.
const CLOUD_PROVIDER_SWITCH_PREFIX: &str = "CLAUDE_CODE_USE_";

/// `apiKeySource` of a run that authenticates without an API key.
const NO_API_KEY_SOURCE: &str = "none";

/// `modelUsage` provider of Anthropic's own API, which a Claude
/// subscription login uses.
const FIRST_PARTY_PROVIDER: &str = "firstParty";

/// Checkpoint of a process that reported no totals. It names no totals, so
/// the turn that continues its conversation falls back to list price.
const UNKNOWN_CHECKPOINT: &str = "unknown";

/// Folds Claude Code stream events into the run's usage, under an empty
/// model name, and its `modelUsage` totals.
#[derive(Default)]
pub(crate) struct ClaudeUsageMeter {
    /// Fill of the latest main-loop response.
    context: Option<ContextFill>,
    /// Model of the latest main-loop response.
    context_model: Option<String>,
    /// Whether the latest result's `modelUsage` names Anthropic's own API as
    /// the provider of every model, or `None` before a result reports it.
    is_first_party: Option<bool>,
    /// Whether the `system/init` event reported that the run uses no API
    /// key.
    is_without_api_key: bool,
    /// Per-model totals of the latest result's `modelUsage`.
    model_totals: BTreeMap<String, ModelTotals>,
    /// Summed main-loop usage of the run's turn results.
    results: Option<ModelUsage>,
    /// Ids of the main-loop responses already counted.
    seen_messages: HashSet<String>,
    /// Summed usage of the main-loop responses, with placeholder output.
    steps: Option<ModelUsage>,
    /// Whether the process runs with alternate credentials, which bill per
    /// token.
    uses_alternate_credentials: bool,
    /// Claude Code release from the `system/init` event.
    version: Option<Version>,
    /// Context window of each model, from a result's `modelUsage`.
    windows: HashMap<String, u64>,
}

impl ClaudeUsageMeter {
    /// Folds one stream event and returns whether it reported usage: a
    /// main-loop response not counted yet, or a turn result.
    pub(crate) fn observe(&mut self, event: &Value) -> bool {
        if event.get("type").and_then(Value::as_str) == Some("system") {
            if let Some(version) = event
                .get("claude_code_version")
                .and_then(Value::as_str)
                .and_then(|version| Version::parse(version).ok())
            {
                self.version = Some(version);
            }
            if let Some(source) = event.get("apiKeySource").and_then(Value::as_str) {
                self.is_without_api_key = source == NO_API_KEY_SOURCE;
            }
        }
        if let Some(model_usage) = event.get("modelUsage").and_then(Value::as_object) {
            self.model_totals.clear();
            self.is_first_party = Some(model_usage.values().all(|usage| {
                usage.get("provider").and_then(Value::as_str) == Some(FIRST_PARTY_PROVIDER)
            }));
            for (model, usage) in model_usage {
                if let Some(window) = usage.get("contextWindow").and_then(Value::as_u64) {
                    self.windows.insert(model.clone(), window);
                }
                if let Some(totals) = ModelTotals::parse(usage) {
                    self.model_totals.insert(model.clone(), totals);
                }
            }
        }
        if let Some(usage) = event.get("usage") {
            fold(&mut self.results, &response_usage(usage));

            return true;
        }

        self.observe_response(event)
    }

    /// Folds one stream line: a single event, or an array of events as one
    /// complete `json` payload carries them.
    pub(crate) fn observe_payload(&mut self, payload: &Value) {
        match payload.as_array() {
            Some(events) => {
                for event in events {
                    self.observe(event);
                }
            }
            None => {
                self.observe(payload);
            }
        }
    }

    /// Returns the run's main-loop usage: its results' usage, or before any
    /// result the responses observed so far, or one unreported request when
    /// Claude reported nothing.
    pub(crate) fn usage(&self) -> ModelUsage {
        let mut usage = self
            .results
            .clone()
            .or_else(|| self.steps.clone())
            .unwrap_or_else(|| ModelUsage::unreported("", 1));
        let responses = u32::try_from(self.seen_messages.len()).unwrap_or(u32::MAX);
        usage.requests = usage.requests.max(responses);
        usage.context = self.context.map(|context| ContextFill {
            window_tokens: self
                .context_model
                .as_ref()
                .and_then(|model| self.windows.get(model))
                .copied(),
            ..context
        });

        usage
    }

    /// Returns how the run is billed.
    ///
    /// Claude Code reports `apiKeySource: "none"` for a Claude subscription
    /// login, but also for a bearer token, a gateway, or a cloud provider
    /// such as Amazon Bedrock, Google Vertex AI, or Microsoft Foundry, which
    /// bill per token. A run is therefore plan-billed only when it used no
    /// API key and its `modelUsage` names Anthropic's own API
    /// (`firstParty`) as every model's provider. Any other provider, or a
    /// release that reports none, leaves the run metered.
    pub(crate) fn billing(&self) -> Billing {
        if !self.uses_alternate_credentials
            && self.is_without_api_key
            && self.is_first_party == Some(true)
        {
            return Billing::Plan(PlanLogin::Claude);
        }

        Billing::Metered
    }

    /// Returns how the run is billed as far as it is known so far, or
    /// `None` while it may still turn out plan-billed: it uses no API key
    /// and no alternate credentials, and no result has named its provider
    /// yet.
    pub(crate) fn known_billing(&self) -> Option<Billing> {
        (self.uses_alternate_credentials
            || !self.is_without_api_key
            || self.is_first_party.is_some())
        .then(|| self.billing())
    }

    /// Records that the process runs with alternate credentials, as
    /// [`uses_alternate_credentials`] detects them, which bill per token
    /// whatever the run reports.
    pub(crate) fn set_alternate_credentials(&mut self, uses_alternate_credentials: bool) {
        self.uses_alternate_credentials = uses_alternate_credentials;
    }

    /// Returns the run's `modelUsage` totals, or `None` before a result
    /// reports them.
    pub(crate) fn totals(&self) -> Option<AgentTotals> {
        (!self.model_totals.is_empty()).then(|| AgentTotals {
            context_model: self.context_model.clone(),
            models: self.model_totals.clone(),
            version: self.version.clone(),
        })
    }

    /// Counts one main-loop assistant response once per message id. Responses
    /// of subagents, which name the tool call that started them, are left
    /// out, as their turn results leave them out.
    fn observe_response(&mut self, event: &Value) -> bool {
        if event.get("type").and_then(Value::as_str) != Some("assistant")
            || event
                .get("parent_tool_use_id")
                .is_some_and(|parent| !parent.is_null())
        {
            return false;
        }
        let Some(message) = event.get("message") else {
            return false;
        };
        let (Some(id), Some(usage)) = (
            message.get("id").and_then(Value::as_str),
            message.get("usage"),
        ) else {
            return false;
        };
        if !self.seen_messages.insert(id.to_string()) {
            return false;
        }
        let response = response_usage(usage);
        let fill = ContextFill::of_request(response.input_tokens, None);
        self.context = Some(self.context.map_or(fill, |context| context.then(fill)));
        self.context_model = message
            .get("model")
            .and_then(Value::as_str)
            .map(str::to_string);
        fold(&mut self.steps, &response);

        true
    }
}

/// The `modelUsage` totals one Claude Code process reported.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct AgentTotals {
    /// Model of the run's latest main-loop response, whose row carries the
    /// run's context fill.
    context_model: Option<String>,
    /// Cumulative totals of each model.
    models: BTreeMap<String, ModelTotals>,
    /// Claude Code release, when the run reported it.
    version: Option<Version>,
}

/// One model's cumulative counts in a result's `modelUsage`.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
struct ModelTotals {
    /// Input tokens read from the prompt cache.
    cache_read: u64,
    /// Input tokens written to the prompt cache.
    cache_write: u64,
    /// Claude Code's cost estimate in micro-USD, when reported.
    cost: Option<u64>,
    /// Input tokens without the cache.
    input: u64,
    /// Output tokens, thinking included.
    output: u64,
    /// Thinking tokens, when reported.
    thinking: Option<u64>,
}

impl ModelTotals {
    /// Totals of a model a process has not used yet.
    const UNUSED: Self = Self {
        cache_read: 0,
        cache_write: 0,
        cost: Some(0),
        input: 0,
        output: 0,
        thinking: Some(0),
    };

    /// Parses one `modelUsage` entry, which must report input and output.
    fn parse(usage: &Value) -> Option<Self> {
        let count = |field: &str| usage.get(field).and_then(Value::as_u64);

        Some(Self {
            cache_read: count("cacheReadInputTokens").unwrap_or(0),
            cache_write: count("cacheCreationInputTokens").unwrap_or(0),
            // A `costBasis` of `unknown` means no price table matched the
            // model, so its `costUSD` is no estimate.
            cost: usage
                .get("costUSD")
                .filter(|_| usage.get("costBasis").and_then(Value::as_str) != Some("unknown"))
                .and_then(Value::as_f64)
                .and_then(micro_usd),
            input: count("inputTokens")?,
            output: count("outputTokens")?,
            thinking: count("thinkingTokens"),
        })
    }

    /// Returns these totals minus the `earlier` ones, or `None` when a total
    /// went down, as it does when the totals restarted.
    fn since(self, earlier: Self) -> Option<Self> {
        let optional = |current: Option<u64>, earlier: Option<u64>| match (current, earlier) {
            (Some(current), Some(earlier)) => current.checked_sub(earlier).map(Some),
            _ => Some(None),
        };

        Some(Self {
            cache_read: self.cache_read.checked_sub(earlier.cache_read)?,
            cache_write: self.cache_write.checked_sub(earlier.cache_write)?,
            cost: optional(self.cost, earlier.cost)?,
            input: self.input.checked_sub(earlier.input)?,
            output: self.output.checked_sub(earlier.output)?,
            thinking: optional(self.thinking, earlier.thinking)?,
        })
    }

    /// Returns whether these counts include any token.
    fn has_tokens(self) -> bool {
        self.input > 0 || self.output > 0 || self.cache_read > 0 || self.cache_write > 0
    }

    /// Returns these counts as `model`'s usage of one request, priced at
    /// Claude Code's estimate when it reported one, else at list price.
    fn model_usage(self, model: &str) -> ModelUsage {
        let mut usage = ModelUsage {
            cache_read_tokens: Some(self.cache_read),
            cache_write_tokens: Some(self.cache_write),
            input_tokens: self
                .input
                .saturating_add(self.cache_read)
                .saturating_add(self.cache_write),
            output_tokens: self.output,
            reasoning_tokens: self.thinking,
            requests: 1,
            ..ModelUsage::new(model)
        };
        usage.cost = match self.cost {
            Some(micro_usd) => Some(CostEstimate::new(CostBasis::AgentReported, micro_usd)),
            None => list_price(&usage, ModelProvider::Anthropic),
        };

        usage
    }
}

/// Returns whether `command`, started with the environment `process_env`
/// overlaid by the command's own variables, points Claude Code at
/// credentials or an endpoint other than an interactive login: a bearer
/// token (`ANTHROPIC_AUTH_TOKEN`), a custom endpoint (`ANTHROPIC_BASE_URL`),
/// or a cloud provider (any `CLAUDE_CODE_USE_*` switch). Such runs report no
/// API key yet bill per token.
pub(crate) fn uses_alternate_credentials(
    command: &Command,
    process_env: impl IntoIterator<Item = (OsString, OsString)>,
) -> bool {
    let mut environment = process_env.into_iter().collect::<HashMap<_, _>>();
    for (key, value) in command.get_envs() {
        match value {
            Some(value) => environment.insert(key.to_os_string(), value.to_os_string()),
            None => environment.remove(key),
        };
    }

    environment.iter().any(|(key, value)| {
        let key = key.to_string_lossy();
        let is_set = !value.is_empty() && value != "0" && value != "false";

        is_set
            && (ALTERNATE_CREDENTIAL_VARIABLES.contains(&key.as_ref())
                || key.starts_with(CLOUD_PROVIDER_SWITCH_PREFIX))
    })
}

/// One Claude Code process of a turn: its main-loop usage and its
/// `modelUsage` totals, when reported.
pub(crate) struct ClaudeRun<'a> {
    /// How the process was billed; under a plan its costs are API
    /// equivalents.
    pub(crate) billing: Billing,
    /// Main-loop usage, under an empty model name.
    pub(crate) main_loop: &'a ModelUsage,
    /// `modelUsage` totals of the process.
    pub(crate) totals: Option<&'a AgentTotals>,
}

/// Returns the usage of one turn's Claude Code processes on `model`, in the
/// order they ran, and the checkpoint the next continued turn needs.
///
/// A process that continued the conversation (a `SessionResume` request) is
/// charged the difference from `checkpoint`, the totals after the
/// conversation's previous turn. Any other process, such as a session's
/// first turn or a utility prompt, starts at zero and is charged its own
/// totals. A process whose share cannot be trusted, because it reported no
/// totals, its release is unknown, no checkpoint precedes it, or a total
/// went down, is charged its main-loop usage at list price instead.
///
/// Claude Code continues the most recent conversation in the directory, so
/// every process, whatever its request kind, leaves the checkpoint of
/// `folder` the next continued turn there needs: its totals, or
/// [`UNKNOWN_CHECKPOINT`] when it reported none.
pub(crate) fn turn_usage<'a>(
    model: &str,
    request_kind: &AgentRequestKind,
    folder: &Path,
    checkpoint: Option<&str>,
    runs: impl IntoIterator<Item = ClaudeRun<'a>>,
) -> TurnUsage {
    let resumed = request_kind.is_resume();
    let mut previous = checkpoint.and_then(|checkpoint| serde_json::from_str(checkpoint).ok());
    let mut usage = TurnUsage::default();
    for run in runs {
        let models = run
            .totals
            .and_then(|totals| run_share(totals, resumed, previous.as_ref()))
            .unwrap_or_else(|| {
                let mut main_loop = ModelUsage {
                    model: model.to_string(),
                    ..run.main_loop.clone()
                };
                main_loop.cost = list_price(&main_loop, ModelProvider::Anthropic);

                vec![main_loop]
            });
        let context_model = run
            .totals
            .and_then(|totals| totals.context_model.as_deref())
            .filter(|context_model| models.iter().any(|usage| usage.model == *context_model))
            .unwrap_or(model);
        for mut model_usage in models {
            model_usage.cost = run.billing.present(model_usage.cost);
            if model_usage.model == context_model {
                model_usage.context = run.main_loop.context;
                model_usage.requests = model_usage.requests.max(run.main_loop.requests);
            }
            usage.record(&model_usage);
        }
        previous = run.totals.map(|totals| totals.models.clone());
        usage.checkpoint = Some(UsageCheckpoint::new(
            folder,
            previous
                .as_ref()
                .and_then(|models| serde_json::to_string(models).ok())
                .unwrap_or_else(|| UNKNOWN_CHECKPOINT.to_string()),
        ));
    }

    usage
}

/// Returns each model's share of one process's `totals`, or `None` when it
/// cannot be trusted. Models without new work are left out.
fn run_share(
    totals: &AgentTotals,
    resumed: bool,
    previous: Option<&BTreeMap<String, ModelTotals>>,
) -> Option<Vec<ModelUsage>> {
    let restores_earlier_totals = resumed && totals.version.as_ref()? >= &CUMULATIVE_RESUME_VERSION;
    let empty = BTreeMap::new();
    let previous = if restores_earlier_totals {
        previous?
    } else {
        &empty
    };

    totals
        .models
        .iter()
        .map(|(model, current)| {
            let earlier = previous.get(model).copied().unwrap_or(ModelTotals::UNUSED);

            current
                .since(earlier)
                .map(|share| share.has_tokens().then(|| share.model_usage(model)))
        })
        .collect::<Option<Vec<_>>>()
        .map(|shares| shares.into_iter().flatten().collect())
}

/// Converts one Messages usage object into one request's usage, with input
/// counting cache reads and writes.
fn response_usage(usage: &Value) -> ModelUsage {
    let count = |field: &str| usage.get(field).and_then(Value::as_u64);
    let input = count("input_tokens");
    let output = count("output_tokens");
    let cache_read = count("cache_read_input_tokens");
    let cache_write = count("cache_creation_input_tokens");

    ModelUsage {
        cache_read_tokens: cache_read,
        cache_write_tokens: cache_write,
        input_tokens: input
            .unwrap_or(0)
            .saturating_add(cache_read.unwrap_or(0))
            .saturating_add(cache_write.unwrap_or(0)),
        output_tokens: output.unwrap_or(0),
        requests: 1,
        unreported_requests: u32::from(input.is_none() || output.is_none()),
        ..ModelUsage::new("")
    }
}

/// Converts a dollar amount into whole micro-USD, rounded, or `None` for a
/// negative or non-finite amount.
fn micro_usd(dollars: f64) -> Option<u64> {
    format!("{:.0}", dollars * 1_000_000.0).parse().ok()
}

/// Adds `next` to `total`, starting the total when empty.
fn fold(total: &mut Option<ModelUsage>, next: &ModelUsage) {
    match total {
        Some(total) => total.add(next),
        None => *total = Some(next.clone()),
    }
}

#[cfg(test)]
#[path = "claude_usage_test.rs"]
mod tests;