diff --git a/crates/axe-core/src/provider.rs b/crates/axe-core/src/provider.rs index 5c17de7..9356c96 100644 --- a/crates/axe-core/src/provider.rs +++ b/crates/axe-core/src/provider.rs @@ -72,6 +72,11 @@ pub struct Provider { pub claude_models: Option, /// Where people get a key. pub console: &'static str, + /// The provider's public price of one model: this URL with the model + /// appended, answered without a key ([`model_price`]). For a model the + /// run's tool does not price and axe's table has no row for + /// (`usage::PRICES`): Claude Code on OpenRouter. + pub model_price: Option<&'static str>, } pub const PROVIDERS: &[Provider] = &[ @@ -101,6 +106,7 @@ pub const PROVIDERS: &[Provider] = &[ subagent: "deepseek-flash", }), console: "platform.deepseek.com", + model_price: None, }, // https://openrouter.ai/docs/api-reference/api-keys/get-current-key // (GET /api/v1/key, bearer; 401 on a wrong key; `/api/v1/models` is a @@ -129,6 +135,9 @@ pub const PROVIDERS: &[Provider] = &[ subagent: "~anthropic/claude-opus-latest[1m]", }), console: "openrouter.ai/keys", + // https://openrouter.ai/docs/guides/overview/models: `data.pricing` + // in USD per token as strings, "0" free; public (no key, 20261202). + model_price: Some("https://openrouter.ai/api/v1/model/"), }, // https://developers.openai.com/api/reference/resources/models/methods/list // (GET /v1/models, bearer; `data[]` of `{id, object, created, @@ -153,6 +162,7 @@ pub const PROVIDERS: &[Provider] = &[ anthropic_url: None, claude_models: None, console: "platform.openai.com/api-keys", + model_price: None, }, // https://platform.claude.com/docs/en/api/models-list (GET /v1/models, // `limit` 1 to 1000, newest first; `data[]` of `{id, display_name, @@ -180,6 +190,7 @@ pub const PROVIDERS: &[Provider] = &[ anthropic_url: None, claude_models: None, console: "platform.claude.com/settings/keys", + model_price: None, }, // https://aistudio.google.com/api-reference/models/list-models (GET // /v1beta/models, `pageSize` up to 1000; `models[]` of `{name: @@ -205,6 +216,7 @@ pub const PROVIDERS: &[Provider] = &[ anthropic_url: None, claude_models: None, console: "aistudio.google.com/apikey", + model_price: None, }, // Any OpenAI-compatible server (`Other…`): the owner gives its base URL // with the key. Its key check is OpenAI's list models call on that URL @@ -227,6 +239,7 @@ pub const PROVIDERS: &[Provider] = &[ anthropic_url: None, claude_models: None, console: "", + model_price: None, }, ]; @@ -257,6 +270,7 @@ const TEST_PROVIDERS: &[Provider] = &[ anthropic_url: None, claude_models: None, console: "acme.test", + model_price: None, }, Provider { id: "acme2", @@ -274,6 +288,7 @@ const TEST_PROVIDERS: &[Provider] = &[ anthropic_url: None, claude_models: None, console: "acme2.test", + model_price: None, }, ]; @@ -477,6 +492,73 @@ pub fn check_key(call: &Call, key: &str, timeout: Duration) -> KeyCheck { } } +/// How long a price lookup may take: it runs as a run's usage is read. +pub const MODEL_PRICE_TIMEOUT: Duration = Duration::from_secs(5); + +/// Provider `p`'s public price of `model` now ([`Provider::model_price`]), +/// its URL's scheme and host on `base` when set (a mock). `Ok(None)`: the +/// row has no price lookup, or the answer holds no usable price. +pub fn model_price( + p: &Provider, + model: &str, + base: Option<&str>, +) -> Result, String> { + let Some(prefix) = p.model_price else { + return Ok(None); + }; + let mut url = format!("{prefix}{model}"); + if let Some(b) = base { + url = on_base(b, &url); + } + let agent = ureq::AgentBuilder::new() + .timeout(MODEL_PRICE_TIMEOUT) + .redirects(0) + .build(); + let body: serde_json::Value = match agent.get(&url).set("Accept", "application/json").call() { + Ok(r) => r.into_json().map_err(|e| format!("{url}: {e}"))?, + Err(ureq::Error::Status(404, _)) => return Ok(None), + Err(e) => return Err(format!("{url}: {e}")), + }; + Ok(crate::usage::catalog_price(&body["data"]["pricing"])) +} + +/// A node's provider price lookups ([`model_price`]), kept an hour (ten +/// minutes when the lookup failed), so a busy node asks once per model. +#[derive(Default)] +pub struct ModelPrices { + base: Option, + seen: std::collections::HashMap)>, +} + +impl ModelPrices { + /// Lookups go to `base` (`AXE_KEY_CHECK_BASE`, a provider mock) when set. + pub fn new(base: Option) -> ModelPrices { + ModelPrices { + base: base.map(|b| b.trim_end_matches('/').to_string()), + ..Default::default() + } + } + + /// `provider/model`'s price now, from its provider's lookup. + pub fn price(&mut self, key: &str) -> Option { + let (id, model) = key.split_once('/')?; + let p = get(id).filter(|p| p.model_price.is_some())?; + if let Some((at, price)) = self.seen.get(key) { + let ttl = if price.is_some() { 3600 } else { 600 }; + if at.elapsed() < Duration::from_secs(ttl) { + return *price; + } + } + let price = model_price(p, model, self.base.as_deref()).unwrap_or_else(|e| { + eprintln!("axe node: no {} price for {model}: {e}", p.label); + None + }); + self.seen + .insert(key.to_string(), (std::time::Instant::now(), price)); + price + } +} + #[cfg(test)] pub(crate) mod tests { use super::*; @@ -533,6 +615,47 @@ pub(crate) mod tests { (base, rx) } + /// The price lookup asks OpenRouter's public model URL without a key, + /// once per model an hour; a row without one is never asked. + #[test] + fn a_model_price_is_looked_up_once_without_a_key() { + // The mock answers requests carrying the lookup's Accept header. + let (base, rx) = mock_with("application/json", |line| { + let body = match line.contains("/api/v1/model/deepseek/deepseek-v4.1-flash ") { + true => { + r#"{"data":{"id":"deepseek/deepseek-v4.1-flash","pricing":{"prompt":"0.000000051","completion":"0.000000567","input_cache_read":"0.000000018"}}}"# + } + false => r#"{"error":{"code":404}}"#, + }; + ( + if body.contains("error") { 404 } else { 200 }, + body.to_string(), + ) + }); + let mut prices = ModelPrices::new(Some(base)); + let p = prices + .price("openrouter/deepseek/deepseek-v4.1-flash") + .unwrap(); + assert!((p.input - 0.051).abs() < 1e-9 && (p.output - 0.567).abs() < 1e-9); + assert!((p.cached - 0.018).abs() < 1e-9 && (p.cache_write - 0.051).abs() < 1e-9); + let head = rx.recv().unwrap(); + assert!( + head.starts_with("GET /api/v1/model/deepseek/deepseek-v4.1-flash HTTP"), + "{head}" + ); + assert!(!head.to_lowercase().contains("authorization"), "{head}"); + // Kept: no second request. + assert_eq!( + prices.price("openrouter/deepseek/deepseek-v4.1-flash"), + Some(p) + ); + assert!(prices.price("openrouter/acme/none").is_none()); + assert!(rx.recv().unwrap().contains("/acme/none")); + assert!(prices.price("deepseek/deepseek-flash").is_none()); + assert!(prices.price("openrouter/acme/none").is_none()); + assert!(rx.recv_timeout(Duration::from_millis(200)).is_err()); + } + #[test] fn every_provider_row_is_complete() { let mut ids = std::collections::BTreeSet::new(); diff --git a/crates/axe-core/src/runtime.rs b/crates/axe-core/src/runtime.rs index dbfde71..dc0dbf1 100644 --- a/crates/axe-core/src/runtime.rs +++ b/crates/axe-core/src/runtime.rs @@ -197,8 +197,9 @@ impl Default for Health { } /// Sends provider key checks to `http://host:port` + each check's path -/// instead of the provider ([`Registry::with_key_check_base`]): a node in a -/// test or scratch run against a local provider mock. +/// instead of the provider ([`Registry::with_key_check_base`]), and its +/// model price lookups too (`provider::ModelPrices`): a node in a test or +/// scratch run against a local provider mock. pub const KEY_CHECK_BASE_ENV: &str = "AXE_KEY_CHECK_BASE"; /// The node's registry as its main loop last saw it (`managed`, runtimes), @@ -348,8 +349,9 @@ fn base_url_file(p: &crate::provider::Provider) -> &'static str { /// Anthropic-Messages endpoint with `key` as a bearer token, and those it /// must not see: an Anthropic key would be sent along to the provider /// (`x-api-key`), and a setup token would be read ahead of the login dir. -/// `url` is `Other…`'s base URL; it has no tier models, so a rule names -/// its model ([`tier_env`]). +/// A run no rule names a model for runs the row's `default_model` +/// (`ANTHROPIC_MODEL`). `url` is `Other…`'s base URL; it has no default or +/// tier models, so a rule names its model ([`tier_env`]). fn anthropic_env(p: &crate::provider::Provider, key: String, url: Option) -> LoginEnv { let mut set = vec![ ( @@ -363,6 +365,12 @@ fn anthropic_env(p: &crate::provider::Provider, key: String, url: Option ("ANTHROPIC_API_KEY", String::new()), ("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "1".into()), ]; + // The row's default model when no rule names one (`--model` wins over + // it): Claude Code's own default is its Opus alias, which on OpenRouter + // is the row's Opus tier. + if !p.default_model.is_empty() { + set.push(("ANTHROPIC_MODEL", p.default_model.to_string())); + } if let Some(m) = &p.claude_models { set.extend([ ("ANTHROPIC_DEFAULT_OPUS_MODEL", m.opus.to_string()), @@ -2617,6 +2625,8 @@ exit 2 assert_eq!(get("ANTHROPIC_DEFAULT_HAIKU_MODEL"), Some("deepseek-flash")); assert_eq!(get("CLAUDE_CODE_SUBAGENT_MODEL"), Some("deepseek-flash")); assert_eq!(get("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"), Some("1")); + // No rule naming a model: the row's default, not Claude's Opus. + assert_eq!(get("ANTHROPIC_MODEL"), Some("deepseek-flash")); assert_eq!(get("DEEPSEEK_API_KEY"), None); assert_eq!(get("CLAUDE_CODE_OAUTH_TOKEN"), None); assert!(remove.contains(&"CLAUDE_CODE_OAUTH_TOKEN"), "{remove:?}"); @@ -2628,6 +2638,7 @@ exit 2 let (set, _) = rt.env(); assert!(set.contains(&("ANTHROPIC_BASE_URL", "https://openrouter.ai/api".into()))); assert!(set.contains(&("ANTHROPIC_AUTH_TOKEN", or.clone()))); + assert!(set.contains(&("ANTHROPIC_MODEL", "~anthropic/claude-sonnet-latest".into()))); const KEY: &str = "sk-ant-api03-dummy1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; rt.login(&cfg, "api_key", None, KEY).unwrap(); assert!(!login.join("OPENROUTER_API_KEY").exists()); diff --git a/crates/axe-core/src/usage.rs b/crates/axe-core/src/usage.rs index ac15a2f..e7d56c3 100644 --- a/crates/axe-core/src/usage.rs +++ b/crates/axe-core/src/usage.rs @@ -639,6 +639,28 @@ pub fn openai_price(model: &str) -> Option { price_at(&format!("openai/{model}"), 0) } +/// A provider catalog's price (OpenRouter `data.pricing`: USD per token as +/// strings), per million tokens: `prompt` and `completion`, cache reads and +/// writes at `input_cache_read` and `input_cache_write` (the 5-minute write +/// Claude Code asks for), else the prompt price. `None` without a prompt +/// and completion price, or with a negative one. Conditional `overrides` +/// (long prompts, time windows) are per request and not applied: the +/// default-conditions price, an estimate like Claude's own `costUSD`. +pub fn catalog_price(pricing: &Value) -> Option { + let per_m = |k: &str| -> Option { + let v = &pricing[k]; + let n = v.as_str().map_or(v.as_f64(), |s| s.parse().ok())?; + (n >= 0.0).then_some(n * 1e6) + }; + let input = per_m("prompt")?; + Some(Price { + input, + cached: per_m("input_cache_read").unwrap_or(input), + cache_write: per_m("input_cache_write").unwrap_or(input), + output: per_m("completion")?, + }) +} + /// Whether the tool's own cost for a model stands: Claude Code's `costUSD` /// only when it priced the model from its list (`costBasis: "list"`); a log /// that names no basis (every other tool, older Claude Code) is taken as is. @@ -660,6 +682,33 @@ impl Parsed { self } + /// Each `provider/model` of a run on a provider's login + /// ([`Parsed::on_provider`]) that its tool gave no trusted cost and + /// [`PRICES`] has no row for, priced at `price(model)`: its provider's + /// own price now (`provider::ModelPrices`, Claude Code on OpenRouter). + /// Its cost is then known, not $0. Runs that report their own cost + /// (OpenCode) and models the table prices keep theirs. + pub fn priced_by( + mut self, + provider: Option<&str>, + mut price: impl FnMut(&str) -> Option, + ) -> Parsed { + let Some(provider) = provider else { + return self; + }; + let prefix = format!("{provider}/"); + for (model, t) in self.models.iter_mut() { + if !model.starts_with(&prefix) || t.cost >= COST_EPSILON || price_at(model, 0).is_some() + { + continue; + } + if let Some(p) = price(model) { + t.cost = p.cost(t); + } + } + self + } + /// The usage of a run on provider `provider`'s login (Claude Code on /// DeepSeek): each model becomes `provider/model`, without Claude Code's /// `[1m]` suffix, so the server prices it from [`PRICES`] when its tool diff --git a/crates/axe-node/src/dispatch.rs b/crates/axe-node/src/dispatch.rs index a93fc88..9b8ff83 100644 --- a/crates/axe-node/src/dispatch.rs +++ b/crates/axe-node/src/dispatch.rs @@ -148,6 +148,22 @@ pub(crate) fn run_model(rt: &runtime::Runtime, with: Option<&Use>) -> Option, + ) -> crate::usage::Parsed { + let provider = self.priced_provider(agent, provider); + usage + .on_provider(provider) + .priced_by(provider, |m| self.prices.price(m)) + } + /// The provider that bills a run on runtime `agent`: its provider login /// (`provider`, on a runtime whose logins accumulate), else the one /// provider key the runtime holds (Claude Code on DeepSeek). `None` for @@ -179,6 +195,8 @@ pub struct Dispatcher { store: Store, runs: Vec, server_url: Option, + /// Provider prices of models axe's table does not hold (OpenRouter). + prices: crate::provider::ModelPrices, /// Resource admission; `None` when `[resources]` is not configured. gate: Option, admission: admission::Handle, @@ -461,6 +479,11 @@ impl Dispatcher { deferred: Vec::new(), pre_checks: Vec::new(), profiles_unsupported: false, + prices: crate::provider::ModelPrices::new( + std::env::var(crate::runtime::KEY_CHECK_BASE_ENV) + .ok() + .filter(|b| !b.is_empty()), + ), reported: None, hold_path: admission::hold_path(), hold_logged: None, @@ -1882,8 +1905,8 @@ impl Dispatcher { &run.log_path, &crate::usage::transcript_logins(&self.runtimes.runtimes), ) - .with_model(run.model.as_deref()) - .on_provider(self.priced_provider(&run.pick.agent, run.provider)); + .with_model(run.model.as_deref()); + let usage = self.priced(usage, &run.pick.agent, run.provider); // Only a plain exit is classified (a zero one only for a CLI that // exits 0 on a failed model call); stops, drains and aborts keep their path. let failure = block_note diff --git a/crates/axe-node/src/dispatch/bots.rs b/crates/axe-node/src/dispatch/bots.rs index 72cf383..3147beb 100644 --- a/crates/axe-node/src/dispatch/bots.rs +++ b/crates/axe-node/src/dispatch/bots.rs @@ -630,8 +630,8 @@ impl Dispatcher { &run.log_path, &crate::usage::transcript_logins(&self.runtimes.runtimes), ) - .with_model(run.model.as_deref()) - .on_provider(self.priced_provider(&run.agent, run.provider)); + .with_model(run.model.as_deref()); + let usage = self.priced(usage, &run.agent, run.provider); // A failed exit caused by quota, credit, login or provider is not the // bot's failure (Pi exits 0 after a failed model call). let outage = (reason == "exit") diff --git a/crates/axe/tests/usage.rs b/crates/axe/tests/usage.rs index 48b9911..6b68cb1 100644 --- a/crates/axe/tests/usage.rs +++ b/crates/axe/tests/usage.rs @@ -1515,6 +1515,102 @@ fn claude_code_on_a_provider_is_priced_from_the_table() { assert_eq!(both.models["deepseek/deepseek-flash"].input, 15); } +/// Claude Code on OpenRouter: the model has no table row and Claude's own +/// figure is not trusted, so the node prices it at OpenRouter's own price +/// (`provider::ModelPrices`); each resumed run's delta keeps its share. +#[test] +fn claude_code_on_openrouter_is_priced_at_openrouters_price() { + let m = "openrouter/deepseek/deepseek-v4.1-flash"; + // OpenRouter's `data.pricing` for the model on 20261202: no cache write. + let price = usage::catalog_price(&json!({ + "prompt": "0.000000051", "completion": "0.000000567", + "input_cache_read": "0.000000018" + })) + .unwrap(); + let per_m = (0.051, 0.018, 0.051, 0.567); + let mut asked = vec![]; + let run = |input: i64, asked: &mut Vec| { + known("s", &[("deepseek/deepseek-v4.1-flash", totals(input, 0.0))]) + .on_provider(Some("openrouter")) + .priced_by(Some("openrouter"), |k| { + asked.push(k.to_string()); + Some(price) + }) + }; + let (u1, u2) = (run(10_000, &mut asked), run(30_000, &mut asked)); + assert_eq!(asked, [m, m]); + let (_d, c) = open(); + seed_runs(&c, 2); + started(&c, 1, "2026-12-01T07:00:00Z"); + started(&c, 2, "2026-12-01T08:00:00Z"); + record(&c, 1, &u1); + record(&c, 2, &u2); + near(row(&c, 1, m).2, priced(&totals(10_000, 0.0), per_m)); + near(row(&c, 2, m).2, priced(&totals(20_000, 0.0), per_m)); + assert!(row(&c, 1, m).2.unwrap() > 0.0); + + // A table row, a trusted figure and another provider are never looked up. + let mut asked = 0; + let other = known( + "t", + &[ + ("deepseek-flash", totals(10, 0.0)), + ("deepseek/deepseek-v4-pro", totals(10, 0.0)), + ], + ) + .on_provider(Some("deepseek")) + .priced_by(Some("deepseek"), |_| { + asked += 1; + None + }); + let mine = known("t", &[("anthropic/claude-opus-5.5", totals(10, 0.3))]) + .on_provider(Some("openrouter")) + .priced_by(Some("openrouter"), |_| { + asked += 1; + None + }); + let none = known("t", &[("claude-opus-5-5", totals(10, 0.0))]).priced_by(None, |_| { + asked += 1; + None + }); + assert_eq!(asked, 0); + assert_eq!(other.models["deepseek/deepseek-flash"].cost, 0.0); + assert_eq!( + mine.models["openrouter/anthropic/claude-opus-5.5"].cost, + 0.3 + ); + assert_eq!(none.models["claude-opus-5-5"].cost, 0.0); + // No price found: the tokens stay, at $0 as before. + let unpriced = known("t", &[("x/y", totals(10, 0.0))]) + .on_provider(Some("openrouter")) + .priced_by(Some("openrouter"), |_| None); + assert_eq!(unpriced.models["openrouter/x/y"].cost, 0.0); +} + +#[test] +fn a_catalog_price_is_per_token_in_usd() { + let p = usage::catalog_price(&json!({ + "prompt": "0.000004", "completion": "0.00002", + "input_cache_read": "0.0000002", "input_cache_write": "0.000005", + "overrides": [{"min_prompt_tokens": 200000, "prompt": "0.000008"}] + })) + .unwrap(); + let close = |a: f64, b: f64| assert!((a - b).abs() < 1e-9, "{a} != {b}"); + close(p.input, 4.0); + close(p.output, 20.0); + close(p.cached, 0.2); + close(p.cache_write, 5.0); + // Free, missing or negative ("-1": a router with no fixed price). + assert_eq!( + usage::catalog_price(&json!({"prompt": "0", "completion": "0"})) + .map(|p| p.input + p.output), + Some(0.0) + ); + assert!(usage::catalog_price(&json!({"prompt": "-1", "completion": "-1"})).is_none()); + assert!(usage::catalog_price(&json!({"prompt": "0.1"})).is_none()); + assert!(usage::catalog_price(&Value::Null).is_none()); +} + #[test] fn claude_list_cost_is_trusted_and_others_are_not() { let d = tempfile::tempdir().unwrap(); diff --git a/docs/user/concepts/routines-bots-goals.md b/docs/user/concepts/routines-bots-goals.md index 620feec..3ab598a 100644 --- a/docs/user/concepts/routines-bots-goals.md +++ b/docs/user/concepts/routines-bots-goals.md @@ -75,12 +75,18 @@ at the window its run started in. A Claude run's cost is the `costUSD` that Claude Code reports when it priced the model from its list (`costBasis: "list"`); a figure it made up for a model it does not know counts as none. A run on a provider's login (Claude Code on DeepSeek) records -its models as `provider/model`, without Claude Code's `[1m]` suffix. A Codex +its models as `provider/model`, without Claude Code's `[1m]` suffix. A model +on such a login with neither figure nor table row is priced by the node at +its provider's own public price when the row has a price lookup +(`Provider::model_price`; OpenRouter's `GET /api/v1/model/`, kept an +hour): its default-conditions price, without per-request overrides such as +long-prompt tiers. A Codex run's tokens come from the running total in `codex exec --json`. Its model comes from the Codex session transcript in the runtime's login directory. Its cost is estimated from the table's OpenAI Standard API prices (`usage::openai_price`). Neither Claude's nor Codex's figure is what a -subscription plan bills. A model with no figure and no table row keeps its +subscription plan bills. A model with no figure, no table row and no +provider price (the lookup failed or the provider has none) keeps its tokens at $0; a Codex run whose transcript is gone does so under the model `codex`. `axe usage backfill` reads Codex transcripts from the node's runtimes. An OpenCode run's tokens and cost are the sum of its diff --git a/docs/user/concepts/runtimes.md b/docs/user/concepts/runtimes.md index 1b403fb..a891ead 100644 --- a/docs/user/concepts/runtimes.md +++ b/docs/user/concepts/runtimes.md @@ -70,9 +70,11 @@ kept as `/login/` (`DEEPSEEK_API_KEY`) and checked at once with the key check, which is also the runtime's probe. On Claude a provider login replaces the last login like any other, and the run gets `ANTHROPIC_BASE_URL`, the key as `ANTHROPIC_AUTH_TOKEN` (a bearer), the row's -model per tier (`ANTHROPIC_DEFAULT_*_MODEL`, `CLAUDE_CODE_SUBAGENT_MODEL`) and -an empty `ANTHROPIC_API_KEY`, never an Anthropic credential -(`Runtime::env`). A rule's model that is none of the row's tier models +default model as `ANTHROPIC_MODEL` (a rule's model wins over it as +`--model`; without it Claude Code's own default, its Opus alias, would run +the row's Opus tier), the row's model per tier (`ANTHROPIC_DEFAULT_*_MODEL`, +`CLAUDE_CODE_SUBAGENT_MODEL`) and an empty `ANTHROPIC_API_KEY`, never an +Anthropic credential (`Runtime::env`). A rule's model that is none of the row's tier models (`claude-code:openrouter/deepseek/deepseek-v4-flash`) takes every tier, so Claude Code's background and subagent calls stay on it (`runtime::tier_env`). From Telegram this login is *Other provider…*