Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

Merge PR #7286 charged cost reporting with current build fixes

Steven Enamakelf9f1f16ffddf
diff --cc app/src/store/chatRuntimeSlice.test.ts
index 1299f8a8ec,728b42dc39..4fc89b0893
--- a/app/src/store/chatRuntimeSlice.test.ts
+++ b/app/src/store/chatRuntimeSlice.test.ts
@@@ -1000,130 -1035,69 +1041,197 @@@ describe('hydrateRuntimeFromSnapshot �
});
});
+// Regression: an async sub-agent's approval (`detached`) was routed to the
+// parent thread while the parent turn ran, then wiped by that turn's
+// `chat_done` — "a parked gate cannot outlive its turn" — though its gate was
+// still parked. Every async `image_agent` approval then expired unseen at
+// 600s. A detached card survives turn-end clears and goes on its decision.
+describe('detached approvals', () => {
+ const detached = {
+ requestId: 'req-sub',
+ toolName: 'media_generate_image',
+ message: 'Run media_generate_image',
+ detached: true,
+ };
+
+ it('survives the parent turn ending', () => {
+ const store = makeStore();
+ store.dispatch(setPendingApprovalForThread({ threadId: 't1', approval: detached }));
+ store.dispatch(clearTurnApprovalForThread({ threadId: 't1' }));
+ store.dispatch(turnSettled({ threadId: 't1' }));
+ store.dispatch(clearRuntimeForThread({ threadId: 't1' }));
+ expect(store.getState().chatRuntime.pendingApprovalByThread['t1']?.requestId).toBe('req-sub');
+ });
+
+ it('still clears an in-turn approval at the turn end', () => {
+ const store = makeStore();
+ store.dispatch(
+ setPendingApprovalForThread({
+ threadId: 't1',
+ approval: { requestId: 'req-main', toolName: 'shell', message: 'Run ls' },
+ })
+ );
+ store.dispatch(clearTurnApprovalForThread({ threadId: 't1' }));
+ expect(store.getState().chatRuntime.pendingApprovalByThread['t1']).toBeUndefined();
+ });
+
+ it('clears on its own decision but not on another request', () => {
+ const store = makeStore();
+ store.dispatch(setPendingApprovalForThread({ threadId: 't1', approval: detached }));
+ store.dispatch(clearPendingApprovalIfRequest({ threadId: 't1', requestId: 'req-other' }));
+ expect(store.getState().chatRuntime.pendingApprovalByThread['t1']).toBeDefined();
+ store.dispatch(clearPendingApprovalIfRequest({ threadId: 't1', requestId: 'req-sub' }));
+ expect(store.getState().chatRuntime.pendingApprovalByThread['t1']).toBeUndefined();
+ });
+
+ // Two async sub-agents parked on the same parent thread: the second card
+ // replaced the first, whose gate then expired unanswered.
+ describe('several on one thread', () => {
+ const second = { ...detached, requestId: 'req-sub-2', toolName: 'media_generate_video' };
+ const shown = (store: ReturnType<typeof makeStore>) =>
+ store.getState().chatRuntime.pendingApprovalByThread['t1']?.requestId;
+
+ it('queues a second detached approval behind the shown one, then promotes it', () => {
+ const store = makeStore();
+ store.dispatch(setPendingApprovalForThread({ threadId: 't1', approval: detached }));
+ store.dispatch(setPendingApprovalForThread({ threadId: 't1', approval: second }));
+ expect(shown(store)).toBe('req-sub');
+ // A replay of the queued request does not duplicate it.
+ store.dispatch(setPendingApprovalForThread({ threadId: 't1', approval: second }));
+ store.dispatch(clearPendingApprovalForThread({ threadId: 't1' }));
+ expect(shown(store)).toBe('req-sub-2');
+ store.dispatch(clearPendingApprovalForThread({ threadId: 't1' }));
+ expect(shown(store)).toBeUndefined();
+ });
+
+ it('drops a queued approval on its own decision or expiry, keeping the shown one', () => {
+ const store = makeStore();
+ store.dispatch(setPendingApprovalForThread({ threadId: 't1', approval: detached }));
+ store.dispatch(setPendingApprovalForThread({ threadId: 't1', approval: second }));
+ store.dispatch(clearPendingApprovalIfRequest({ threadId: 't1', requestId: 'req-sub-2' }));
+ expect(shown(store)).toBe('req-sub');
+ store.dispatch(setPendingApprovalForThread({ threadId: 't1', approval: second }));
+ store.dispatch(
+ resolvePendingApprovalForThread({
+ threadId: 't1',
+ requestId: 'req-sub-2',
+ resolution: 'expired',
+ })
+ );
+ store.dispatch(clearPendingApprovalIfRequest({ threadId: 't1', requestId: 'req-sub' }));
+ expect(shown(store)).toBeUndefined();
+ });
+
+ it("never displaces the parent turn's waiting approval with a detached one", () => {
+ const store = makeStore();
+ store.dispatch(
+ setPendingApprovalForThread({
+ threadId: 't1',
+ approval: { requestId: 'req-main', toolName: 'shell', message: 'Run ls' },
+ })
+ );
+ store.dispatch(setPendingApprovalForThread({ threadId: 't1', approval: detached }));
+ expect(shown(store)).toBe('req-main');
+ store.dispatch(clearTurnApprovalForThread({ threadId: 't1' }));
+ expect(shown(store)).toBe('req-sub');
+ });
+
+ it("shows the parent turn's own approval first and keeps the detached one queued", () => {
+ const store = makeStore();
+ store.dispatch(setPendingApprovalForThread({ threadId: 't1', approval: detached }));
+ store.dispatch(
+ setPendingApprovalForThread({
+ threadId: 't1',
+ approval: { requestId: 'req-main', toolName: 'shell', message: 'Run ls' },
+ })
+ );
+ expect(shown(store)).toBe('req-main');
+ store.dispatch(clearTurnApprovalForThread({ threadId: 't1' }));
+ expect(shown(store)).toBe('req-sub');
+ });
+ });
+
+ // A core restart (or a missed `approval_decided`) leaves a detached card the
+ // core no longer holds. Disconnect reconciliation drops every detached card
+ // so the rejoin replay re-sends only the parks still live.
+ it('drops every detached approval on the thread for reconciliation', () => {
+ const store = makeStore();
+ store.dispatch(setPendingApprovalForThread({ threadId: 't1', approval: detached }));
+ store.dispatch(
+ setPendingApprovalForThread({
+ threadId: 't1',
+ approval: { ...detached, requestId: 'req-sub-2' },
+ })
+ );
+ store.dispatch(dropDetachedApprovalsForThread({ threadId: 't1' }));
+ expect(store.getState().chatRuntime.pendingApprovalByThread['t1']).toBeUndefined();
+ expect(store.getState().chatRuntime.queuedApprovalsByThread['t1']).toBeUndefined();
+ });
+});
++
+ describe('chatRuntimeSlice cost certainty', () => {
+ it('adds reported charges and keeps the thread charged', () => {
+ const store = makeStore();
+ store.dispatch(
+ recordChatTurnUsage({ inputTokens: 10, outputTokens: 1, costUsd: 0.2, costSource: 'charged' })
+ );
+ store.dispatch(recordChatTurnUsage({ inputTokens: 10, outputTokens: 1, costUsd: 0.1 }));
+ const usage = store.getState().chatRuntime.sessionTokenUsage;
+ expect(usage.costUsd).toBeCloseTo(0.3, 9);
+ expect(usage.costSource).toBe('charged');
+ });
+
+ it('marks the thread unknown when a turn reports no cost, and adds nothing for it', () => {
+ // The core sends `null` instead of a guessed rate; it once sent $4.25 for
+ // a glm-5.3-flash thread the provider billed about $0.30.
+ const store = makeStore();
+ store.dispatch(recordChatTurnUsage({ inputTokens: 10, outputTokens: 1, costUsd: 0.2 }));
+ store.dispatch(
+ recordChatTurnUsage({
+ inputTokens: 5_710_657,
+ outputTokens: 30_790,
+ costUsd: null,
+ costSource: 'unknown',
+ })
+ );
+ const usage = store.getState().chatRuntime.sessionTokenUsage;
+ expect(usage.costSource).toBe('unknown');
+ expect(usage.costUsd).toBeCloseTo(0.2, 9);
+ });
+
+ it('carries an estimate as estimated, and a sub-agent with no cost as unknown', () => {
+ const store = makeStore();
+ store.dispatch(
+ recordChatTurnUsage({
+ inputTokens: 10,
+ outputTokens: 1,
+ costUsd: 0.05,
+ costSource: 'estimated',
+ subAgents: [{ agentId: 'researcher', inputTokens: 3, outputTokens: 1, costUsd: null }],
+ })
+ );
+ const usage = store.getState().chatRuntime.sessionTokenUsage;
+ expect(usage.costSource).toBe('estimated');
+ expect(usage.subAgents.researcher.costSource).toBe('unknown');
+ });
+
+ it('hydrates an unknown thread cost from the usage RPC', () => {
+ const store = makeStore();
+ store.dispatch(
+ hydrateThreadUsage({
+ threadId: 'thr-unknown',
+ inputTokens: 7_021_942,
+ outputTokens: 42_669,
+ cachedTokens: 6_466_688,
+ costUsd: null,
+ turns: 3,
+ contextWindow: 1_048_576,
+ lastTurnInputTokens: 5_710_657,
+ lastTurnOutputTokens: 30_790,
+ })
+ );
+ const bucket = store.getState().chatRuntime.usageByThread['thr-unknown'];
+ expect(bucket.costSource).toBe('unknown');
+ expect(bucket.costUsd).toBe(0);
+ });
+ });
diff --cc crates/openhuman-core/src/agent/cost.rs
index 949d25c96b,1276914457..3d3d321bf3
--- a/crates/openhuman-core/src/agent/cost.rs
+++ b/crates/openhuman-core/src/agent/cost.rs
@@@ -43,73 -37,11 +37,24 @@@ pub(crate) struct ModelPricing
pub(crate) output_per_mtok_usd: f64,
}
- /// Conservative fallback when nothing in the table matches. Picked so
- /// budget caps still bite on unknown models rather than reading as $0.
- const FALLBACK_PRICING: ModelPricing = ModelPricing {
- model: "<fallback>",
- input_per_mtok_usd: 3.00,
- cached_input_per_mtok_usd: 0.30,
- output_per_mtok_usd: 15.00,
- };
-
- /// Static price table for the managed default model.
- const PRICING_TABLE: &[ModelPricing] = &[
- // The managed default model — DeepSeek V4 Flash through the OpenRouter
- // passthrough. Estimate only; the backend's echoed `charged_amount_usd` is
- // authoritative when present. Any other catalog model the user pins is
- // priced from the vendor catalog (`platform::cost::catalog`) below.
- ModelPricing {
- model: crate::config::MODEL_MANAGED_DEFAULT,
- input_per_mtok_usd: 0.0886,
- cached_input_per_mtok_usd: 0.0886,
- output_per_mtok_usd: 0.1772,
- },
- ];
-
- /// Legacy tier slugs from older transcripts and configs, mapped onto the
- /// managed default's rate so an old cost record still estimates sanely.
- const LEGACY_TIER_ROWS: &[&str] = &crate::config::LEGACY_TIER_MODELS;
-
- /// Zero-rate pricing for free model variants (OpenRouter's `…:free` ids).
- const FREE_PRICING: ModelPricing = ModelPricing {
- model: "<free>",
- input_per_mtok_usd: 0.0,
- cached_input_per_mtok_usd: 0.0,
- output_per_mtok_usd: 0.0,
- };
-
- /// Whether `model` names a free variant: OpenRouter's `vendor/model:free`
- /// suffix (case-insensitive, optionally behind a provider prefix such as
- /// `openrouter.` or `openrouter/`).
+ /// Published list rates for `model`, or `None` when the vendor catalog does
+ /// not know it.
++/// Whether a model names an explicitly free OpenRouter variant.
+pub(crate) fn is_free_model(model: &str) -> bool {
+ model.trim().to_ascii_lowercase().ends_with(":free")
+}
+
- /// Look up pricing for a model name when it is actually known, or `None`.
- ///
- /// Resolution order:
- /// 1. A free variant (`…:free`) is priced at zero.
- /// 2. Exact match on the managed default model (or a retired tier slug /
- /// `hint:*` alias, which ran on it).
- /// 3. The concrete-vendor-model pricing catalog
- /// ([`crate::platform::cost::catalog`]) — accurate per-model rates for
- /// `claude-*`, `gpt-*`, `gemini-*`, `deepseek-*`, `kimi-*`, `qwen-*`,
- /// `mistral-*`, including OpenRouter-style `vendor/model` ids.
- ///
- /// Reporting surfaces (trace export, journal roll-ups) use this so an unknown
- /// model records no cost rather than a made-up one.
- pub(crate) fn lookup_known_pricing(model: &str) -> Option<ModelPricing> {
- let trimmed = model.trim();
- if is_free_model(trimmed) {
- return Some(FREE_PRICING);
- }
- if let Some(row) = PRICING_TABLE.iter().find(|row| row.model == trimmed) {
- return Some(*row);
+ pub(crate) fn lookup_pricing(model: &str) -> Option<ModelPricing> {
++ if is_free_model(model) {
++ return Some(ModelPricing {
++ model: "<free>",
++ input_per_mtok_usd: 0.0,
++ cached_input_per_mtok_usd: 0.0,
++ output_per_mtok_usd: 0.0,
++ });
+ }
- if trimmed.starts_with("hint:") || LEGACY_TIER_ROWS.contains(&trimmed) {
- return Some(PRICING_TABLE[0]);
- }
- crate::platform::cost::catalog::lookup(model).map(|price| ModelPricing {
+ let price = crate::platform::cost::catalog::lookup(model.trim())?;
+ Some(ModelPricing {
model: price.model_id,
input_per_mtok_usd: price.input_per_mtok_usd,
cached_input_per_mtok_usd: price.cached_input_per_mtok_usd,
diff --cc crates/openhuman-core/src/agent/cost_tests.rs
index 9a73526045,37bb064299..970e217b14
--- a/crates/openhuman-core/src/agent/cost_tests.rs
+++ b/crates/openhuman-core/src/agent/cost_tests.rs
@@@ -73,61 -70,17 +70,41 @@@ fn a_turn_with_any_unknown_call_has_no_
}
#[test]
- fn turn_cost_accumulates_charged_and_estimated_separately() {
- let mut tc = TurnCost::new();
- tc.add_call(FLASH, &usage(0, 0, 0, 0.10));
- tc.add_call(FLASH, &usage(1_000_000, 0, 0, 0.0)); // est: 0.0886
- assert_eq!(tc.call_count, 2);
- assert!((tc.charged_usd - 0.10).abs() < 1e-6);
- assert!((tc.estimated_usd - 0.0886).abs() < 1e-6);
- assert!((tc.total_usd() - 0.1886).abs() < 1e-6);
- }
+ fn merged_tallies_keep_the_least_certain_source() {
+ let mut parent = CostTally::default();
+ parent.add(CallCost::Charged(1.0));
+ let mut child = CostTally::default();
+ child.add(CallCost::Estimated(0.25));
+ parent.merge(child);
+ assert_eq!(parent.source, CostSource::Estimated);
+ assert_eq!(parent.usd(), Some(1.25));
- #[test]
- fn turn_cost_aggregates_token_counts() {
- let mut tc = TurnCost::new();
- tc.add_call(FLASH, &usage(100, 50, 20, 0.0));
- tc.add_call(FLASH, &usage(200, 75, 0, 0.0));
- assert_eq!(tc.input_tokens, 300);
- assert_eq!(tc.output_tokens, 125);
- assert_eq!(tc.cached_input_tokens, 20);
+ let mut unknown = CostTally::default();
+ unknown.add(CallCost::Unknown);
+ parent.merge(unknown);
+ assert_eq!(parent.usd(), None);
}
+
+#[test]
+fn free_models_are_priced_at_zero() {
- // OpenRouter `:free` variants are not billed; the catalog would otherwise
- // price `deepseek/...:free` like its paid sibling, or the fallback at $3/$15.
+ for model in [
+ "deepseek/deepseek-chat-v3.1:free",
+ "openrouter/meta-llama/llama-3.3-70b-instruct:free",
+ "Totally-Unknown-Model:FREE",
+ ] {
+ assert!(is_free_model(model), "{model}");
- let usage = usage(1_000_000, 1_000_000, 0, 0.0);
- assert_eq!(estimate_call_cost_usd(model, &usage), 0.0, "{model}");
- assert_eq!(estimate_known_call_cost_usd(model, &usage), Some(0.0));
- assert_eq!(call_cost_usd(model, &usage), 0.0);
++ let usage = counts(1_000_000, 1_000_000, 0);
++ assert_eq!(estimate_call_cost_usd(model, &usage), Some(0.0), "{model}");
++ assert_eq!(call_cost(model, &usage), CallCost::Estimated(0.0));
+ }
+ assert!(!is_free_model("deepseek/deepseek-chat"));
+}
+
+#[test]
+fn unknown_model_has_no_known_price() {
- assert!(lookup_known_pricing("totally-unknown-model").is_none());
- assert_eq!(
- estimate_known_call_cost_usd("totally-unknown-model", &usage(1_000, 100, 0, 0.0)),
- None,
- "reporting must not fabricate a cost for an unpriced model"
- );
- // Budget enforcement still sees the conservative fallback.
- assert!(estimate_call_cost_usd("totally-unknown-model", &usage(1_000, 100, 0, 0.0)) > 0.0);
- }
-
- #[test]
- fn known_model_estimate_matches_budget_estimate() {
- let usage = usage(10_000, 2_000, 4_000, 0.0);
++ assert!(lookup_pricing("totally-unknown-model").is_none());
+ assert_eq!(
- estimate_known_call_cost_usd(FLASH, &usage),
- Some(estimate_call_cost_usd(FLASH, &usage))
++ estimate_call_cost_usd("totally-unknown-model", &counts(1_000, 100, 0)),
++ None
+ );
+}
diff --cc crates/openhuman-core/src/agent/progress_tracing/collector/generation.rs
index 8188761021,0000000000..964d15d3fd
mode 100644,000000..100644
--- a/crates/openhuman-core/src/agent/progress_tracing/collector/generation.rs
+++ b/crates/openhuman-core/src/agent/progress_tracing/collector/generation.rs
@@@ -1,151 -1,0 +1,127 @@@
+//! Pure helpers that shape a generation span's attributes: the model label,
+//! usage normalization across provider routes, cost provenance, and the
+//! unstreamed-call guard for time to first token.
+
- use crate::agent::cost;
- use crate::inference::provider::BilledUsage;
-
+/// A call whose first delta landed this close to its completion was not
+/// streamed: non-streaming providers (the OpenAI Responses path used by the
+/// ChatGPT/Codex sign-in) emit the whole reply as one synthetic delta right
+/// before completing, so its "first token" is just the completion instant.
+pub(super) const UNSTREAMED_DELTA_WINDOW_MS: u64 = 100;
+
+/// Model name to report for a call: the event's own, else the scope's last
+/// known model, else `"unknown"`. A child bridge or a journal completion whose
+/// `ModelStarted` was lost reports an empty name, which surfaced in Langfuse
+/// as `llm.` / model `.`.
+pub(super) fn resolve_model(model: &str, fallback: Option<&str>) -> String {
+ let model = model.trim();
+ if !model.is_empty() {
+ return model.to_string();
+ }
+ fallback
+ .map(str::trim)
+ .filter(|m| !m.is_empty())
+ .unwrap_or("unknown")
+ .to_string()
+}
+
+/// Langfuse-facing model label: `{provider}.{model}`, or the bare model when
+/// the provider is unknown (the journal projection has none), instead of a
+/// dangling `.{model}`.
+pub(super) fn model_label(provider_id: &str, model: &str) -> String {
+ let provider = provider_id.trim();
+ if provider.is_empty() {
+ model.to_string()
+ } else {
+ format!("{provider}.{model}")
+ }
+}
+
+/// One call's token usage in a single convention, whatever the route reported.
+///
+/// Routes disagree on what `input_tokens` means: most (OpenAI-compatible,
+/// OpenRouter, the Anthropic API adapter) report the whole prompt, cache
+/// reads and writes included; the Claude Code route forwards Anthropic's raw
+/// `input_tokens`, which counts only the uncached remainder. Exported as-is,
+/// the second made Langfuse's `total` smaller than the cache read alone. A
+/// prompt-inclusive count can never be below `cache_read + cache_creation`,
+/// so a count that is must be the uncached remainder and is widened here.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(super) struct NormalizedUsage {
+ /// Whole prompt: uncached + cache read + cache creation.
+ pub(super) input_total: u64,
+ /// Prompt tokens neither read from nor written to a cache.
+ pub(super) input_uncached: u64,
+ pub(super) cache_read: u64,
+ pub(super) cache_creation: u64,
+ pub(super) output: u64,
+ /// `input_total + output`.
+ pub(super) total: u64,
+ /// Whether the route reported the uncached remainder and it was widened.
+ pub(super) widened: bool,
+}
+
+pub(super) fn normalize_usage(
+ input_tokens: u64,
+ output_tokens: u64,
+ cache_read: u64,
+ cache_creation: u64,
+) -> NormalizedUsage {
+ let cached = cache_read.saturating_add(cache_creation);
+ let widened = input_tokens < cached;
+ let input_total = if widened {
+ input_tokens.saturating_add(cached)
+ } else {
+ input_tokens
+ };
+ NormalizedUsage {
+ input_total,
+ input_uncached: input_total.saturating_sub(cached),
+ cache_read,
+ cache_creation,
+ output: output_tokens,
+ total: input_total.saturating_add(output_tokens),
+ widened,
+ }
+}
+
+/// Where a generation's cost figure came from.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(super) enum CostSource {
+ /// A provider charge or an estimate from a known price.
+ Priced,
- /// The model has no known price and the reported figure was the
- /// estimator's placeholder rate; no cost is recorded.
++ /// The call has neither a reported charge nor a known estimate.
+ Unpriced,
+}
+
+impl CostSource {
+ pub(super) fn as_str(self) -> &'static str {
+ match self {
+ Self::Priced => "priced",
+ Self::Unpriced => "unpriced",
+ }
+ }
+}
+
- /// The cost to record for a call, and its provenance.
- ///
- /// The live bridge prices a call with [`cost::estimate_call_cost_usd`] when
- /// the provider reports no charge, and that estimator falls back to a
- /// placeholder rate for an unknown model (kept there so budget caps still
- /// bite). On a trace that placeholder reads as a real charge, so a figure
- /// that is exactly the placeholder estimate for an unpriced model is dropped:
- /// the generation carries no cost and Langfuse falls back to its own model
- /// price table, if it has one. A provider charge differs from that estimate
- /// and is kept.
- pub(super) fn effective_cost(
- model: &str,
- input_tokens: u64,
- output_tokens: u64,
- cache_read: u64,
- reported_usd: f64,
- ) -> (f64, CostSource) {
- if cost::lookup_known_pricing(model).is_some() {
- return (reported_usd, CostSource::Priced);
- }
- let placeholder = cost::estimate_call_cost_usd(
- model,
- &BilledUsage::from_counts(input_tokens, output_tokens).with_cached_input_tokens(cache_read),
- );
- if (reported_usd - placeholder).abs() <= 1e-12 {
- (0.0, CostSource::Unpriced)
++/// Preserve the optional cost supplied by the call's accounting layer.
++/// Unknown costs stay absent; a reported zero remains a known price.
++pub(super) fn effective_cost(reported_usd: Option<f64>) -> (Option<f64>, CostSource) {
++ let source = if reported_usd.is_some() {
++ CostSource::Priced
+ } else {
- (reported_usd, CostSource::Priced)
- }
++ CostSource::Unpriced
++ };
++ (reported_usd, source)
+}
+
+/// Whether a call with these delta stamps was really streamed. A call is
+/// treated as unstreamed when its first delta arrived within
+/// [`UNSTREAMED_DELTA_WINDOW_MS`] of completion but well after it started:
+/// that delta carries the completion instant, not a first token.
+pub(super) fn is_unstreamed(first_delta_ms: u64, start_ms: u64, end_ms: u64) -> bool {
+ end_ms.saturating_sub(first_delta_ms) <= UNSTREAMED_DELTA_WINDOW_MS
+ && first_delta_ms.saturating_sub(start_ms) > UNSTREAMED_DELTA_WINDOW_MS
+}
+
+#[cfg(test)]
+#[path = "generation_tests.rs"]
+mod tests;
diff --cc crates/openhuman-core/src/agent/progress_tracing/collector/generation_tests.rs
index 32700b5ea1,0000000000..e789578730
mode 100644,000000..100644
--- a/crates/openhuman-core/src/agent/progress_tracing/collector/generation_tests.rs
+++ b/crates/openhuman-core/src/agent/progress_tracing/collector/generation_tests.rs
@@@ -1,77 -1,0 +1,60 @@@
+use super::*;
+
+#[test]
+fn model_label_skips_an_empty_provider() {
+ assert_eq!(model_label("managed", "chat-v1"), "managed.chat-v1");
+ assert_eq!(
+ model_label("", "openrouter/deepseek/deepseek-v4-flash"),
+ "openrouter/deepseek/deepseek-v4-flash"
+ );
+ assert_eq!(model_label(" ", "m"), "m");
+}
+
+#[test]
+fn resolve_model_falls_back_for_an_empty_name() {
+ assert_eq!(resolve_model("gpt-4o", Some("other")), "gpt-4o");
+ assert_eq!(resolve_model("", Some("deepseek")), "deepseek");
+ assert_eq!(resolve_model(" ", None), "unknown");
+}
+
+#[test]
+fn prompt_inclusive_usage_is_kept() {
+ // deepseek/OpenRouter route: input already counts the cache read.
+ let usage = normalize_usage(66_732, 484, 64_768, 0);
+ assert!(!usage.widened);
+ assert_eq!(usage.input_total, 66_732);
+ assert_eq!(usage.input_uncached, 1_964);
+ assert_eq!(usage.total, 67_216);
+}
+
+#[test]
+fn uncached_only_input_is_widened() {
+ // Claude Code route: Anthropic's raw `input_tokens` is the uncached
+ // remainder, so the reported total used to be smaller than the cache read.
+ let usage = normalize_usage(12, 300, 40_000, 2_000);
+ assert!(usage.widened);
+ assert_eq!(usage.input_total, 42_012);
+ assert_eq!(usage.input_uncached, 12);
+ assert_eq!(usage.cache_read, 40_000);
+ assert_eq!(usage.cache_creation, 2_000);
+ assert_eq!(usage.total, 42_312);
+ assert_eq!(
+ usage.total,
+ usage.input_uncached + usage.cache_read + usage.cache_creation + usage.output
+ );
+}
+
+#[test]
- fn placeholder_cost_for_unpriced_model_is_dropped() {
- let model = "acme/never-heard-of-it";
- let placeholder = crate::agent::cost::estimate_call_cost_usd(
- model,
- &BilledUsage::from_counts(1_000, 100).with_cached_input_tokens(200),
- );
- assert!(placeholder > 0.0);
- assert_eq!(
- effective_cost(model, 1_000, 100, 200, placeholder),
- (0.0, CostSource::Unpriced)
- );
- // A provider charge is not the placeholder and is kept.
- assert_eq!(
- effective_cost(model, 1_000, 100, 200, 0.5),
- (0.5, CostSource::Priced)
- );
- // Free variants are a known zero price.
- assert_eq!(
- effective_cost("x/y:free", 1_000, 100, 0, 0.0),
- (0.0, CostSource::Priced)
- );
++fn unknown_cost_is_absent_and_reported_zero_is_preserved() {
++ assert_eq!(effective_cost(None), (None, CostSource::Unpriced));
++ assert_eq!(effective_cost(Some(0.5)), (Some(0.5), CostSource::Priced));
++ assert_eq!(effective_cost(Some(0.0)), (Some(0.0), CostSource::Priced));
+}
+
+#[test]
+fn single_delta_at_completion_is_unstreamed() {
+ assert!(is_unstreamed(4_990, 1_000, 5_000));
+ assert!(!is_unstreamed(1_300, 1_000, 5_000));
+ // A fast call is not second-guessed.
+ assert!(!is_unstreamed(1_050, 1_000, 1_060));
+}
diff --cc crates/openhuman-core/src/agent/progress_tracing/collector/model_call.rs
index 194cb52a0f,d5ba8f16ce..f4dfdae7be
--- a/crates/openhuman-core/src/agent/progress_tracing/collector/model_call.rs
+++ b/crates/openhuman-core/src/agent/progress_tracing/collector/model_call.rs
@@@ -102,68 -73,16 +102,62 @@@ impl SpanCollector
.and_then(|idx| self.spans.get(idx))
.map(|span| span.start_unix_ms)
.unwrap_or(now_unix_ms);
- // Consume this call's first-delta stamps so the next call on the same
- // iteration (a retry, a repair) starts clean.
- let first_deltas = match subagent_task_id.and_then(|id| self.subagents.get_mut(id)) {
- Some(state) => std::mem::take(&mut state.first_deltas),
- None if subagent_task_id.is_some() => Default::default(),
- None => std::mem::take(&mut self.first_deltas),
+ let start_unix_ms = clock
+ .explicit_start_unix_ms
+ .unwrap_or_else(|| basis_start.max(clock.last_call_end_unix_ms.unwrap_or(0)))
+ .min(now_unix_ms);
+ let model = generation::resolve_model(model, fallback_model.as_deref());
+ // Consume this call's first-delta stamps + start bookkeeping so the
+ // next call on the same iteration (a retry, a repair) starts clean and
+ // after this one.
+ let next_clock = super::state::CallClock {
+ last_call_end_unix_ms: Some(now_unix_ms),
+ explicit_start_unix_ms: None,
+ };
+ let first_deltas = match subagent_task_id {
+ Some(id) => match self.subagent_state_mut(id) {
+ Some(state) => {
+ state.call_clock = next_clock;
+ state.last_raw_model = Some(model.clone());
+ std::mem::take(&mut state.first_deltas)
+ }
+ None => Default::default(),
+ },
+ None => {
+ self.call_clock = next_clock;
+ self.last_raw_model = Some(model.clone());
+ std::mem::take(&mut self.first_deltas)
+ }
};
- let labeled_model = format!("{provider_id}.{model}");
- let pricing = crate::agent::cost::lookup_pricing(model);
+ let labeled_model = generation::model_label(provider_id, &model);
+ // Remember which model this scope is on so the tool spans it requests
+ // name it (correlating tool errors to models without a join). The
+ // label already drops an empty provider (the journal replay has none).
+ match subagent_task_id {
+ Some(id) => {
+ if let Some(state) = self.subagent_state_mut(id) {
+ state.last_model = Some(labeled_model.clone());
+ }
+ }
+ None => self.last_model = Some(labeled_model.clone()),
+ }
- let pricing = crate::agent::cost::lookup_known_pricing(&model);
++ let pricing = crate::agent::cost::lookup_pricing(&model);
+ let usage = generation::normalize_usage(
+ input_tokens,
+ output_tokens,
+ cached_input_tokens,
+ cache_creation_tokens,
+ );
- let (cost_usd, cost_source) = generation::effective_cost(
- &model,
- input_tokens,
- output_tokens,
- cached_input_tokens,
- cost_usd,
- );
++ let (cost_usd, cost_source) = generation::effective_cost(cost_usd);
+ if usage.widened {
+ log::debug!(
+ "[agent-tracing] widened uncached input to prompt-inclusive model={labeled_model} \
+ reported_in={input_tokens} cache_read={cached_input_tokens} \
+ cache_write={cache_creation_tokens} input_total={}",
+ usage.input_total
+ );
+ }
let mut attrs = BTreeMap::new();
attrs.insert("gen_ai.request.model".to_string(), json_str(&labeled_model));
@@@ -204,45 -113,34 +198,48 @@@
json_u64(reasoning_tokens),
);
}
- attrs.insert("gen_ai.usage.cost_usd".to_string(), json_f64(cost_usd));
+ // An unpriced call carries no cost attribute rather than a $0 one.
+ if let Some(cost_usd) = cost_usd {
+ attrs.insert("gen_ai.usage.cost_usd".to_string(), json_f64(cost_usd));
+ }
+ attrs.insert(
+ "gen_ai.cost.source".to_string(),
+ json_str(cost_source.as_str()),
+ );
// Time to first token. Deltas only arrive on streamed calls, so a
- // unary call carries neither attribute. Clamped to the span start: the
- // iteration span opening is the call's approximate start.
- if let Some(first) = first_deltas.any_unix_ms {
- let first = first.max(start_unix_ms);
- attrs.insert(
- "gen_ai.response.first_token_unix_ms".to_string(),
- json_u64(first),
- );
- attrs.insert(
- "gen_ai.response.time_to_first_token_ms".to_string(),
- json_u64(first - start_unix_ms),
- );
- }
- if let Some(first_text) = first_deltas.text_unix_ms {
+ // unary call carries neither attribute; nor does a non-streaming call
+ // whose single synthetic delta lands at completion (its "first token"
+ // would be the whole latency).
+ let unstreamed = first_deltas
+ .any_unix_ms
+ .is_some_and(|first| generation::is_unstreamed(first, start_unix_ms, now_unix_ms));
+ if unstreamed {
attrs.insert(
- "gen_ai.response.time_to_first_text_ms".to_string(),
- json_u64(first_text.max(start_unix_ms) - start_unix_ms),
+ "gen_ai.response.streamed".to_string(),
+ serde_json::Value::Bool(false),
);
+ } else {
+ if let Some(first) = first_deltas.any_unix_ms {
+ let first = first.max(start_unix_ms);
+ attrs.insert(
+ "gen_ai.response.first_token_unix_ms".to_string(),
+ json_u64(first),
+ );
+ attrs.insert(
+ "gen_ai.response.time_to_first_token_ms".to_string(),
+ json_u64(first - start_unix_ms),
+ );
+ }
+ if let Some(first_text) = first_deltas.text_unix_ms {
+ attrs.insert(
+ "gen_ai.response.time_to_first_text_ms".to_string(),
+ json_u64(first_text.max(start_unix_ms) - start_unix_ms),
+ );
+ }
}
// Pricing basis so Langfuse cost figures are auditable against the
- // client-side estimator (USD per million tokens).
- // Omitted for a model the catalog does not price: a made-up basis
- // would make the trace's cost look audited when it is not.
+ // client-side estimator (USD per million tokens). Absent for an
+ // unpriced model rather than showing the placeholder rate.
if let Some(pricing) = pricing {
attrs.insert(
"gen_ai.pricing.input_per_mtok_usd".to_string(),
@@@ -262,8 -160,7 +259,8 @@@
"[agent-tracing] generation span model={labeled_model} \
iteration={iteration} child={} in={input_tokens} out={output_tokens} \
cached={cached_input_tokens} ttft_ms={:?} ttft_text_ms={:?} \
- cost_usd={cost_usd:.6} cost_source={} unstreamed={unstreamed} \
- cost_usd={cost_usd:?} input_captured={} output_captured={}",
++ cost_usd={cost_usd:?} cost_source={} unstreamed={unstreamed} \
+ input_captured={} output_captured={}",
subagent_task_id.is_some(),
first_deltas
.any_unix_ms
diff --cc crates/openhuman-core/src/agent/progress_tracing/journal_projection.rs
index 1365bfade5,147bd2c09b..48b6c7aeed
--- a/crates/openhuman-core/src/agent/progress_tracing/journal_projection.rs
+++ b/crates/openhuman-core/src/agent/progress_tracing/journal_projection.rs
@@@ -480,14 -448,10 +480,14 @@@ fn observation_to_progress(obs: &AgentO
// reported a cache write.
cache_creation_tokens: usage.cache_creation_tokens,
reasoning_tokens: usage.reasoning_tokens,
- cost_usd: 0.0,
+ cost_usd: None,
}];
if scope.is_none() {
- let turn_input = input.as_ref().map(json_content_text);
+ // The request's last user message is the user's own words on
+ // the turn's first call; the collector keeps only the first
+ // turn input, so later calls (whose last user message is tool
+ // results or a harness nudge) do not replace it.
+ let turn_input = input.as_ref().map(user_message_text);
let turn_output = output.as_ref().map(json_content_text);
if turn_input.is_some() || turn_output.is_some() {
progress.push(AgentProgress::TurnContent {
@@@ -525,17 -489,11 +525,17 @@@
// `usage_carry` side-channel, which is not an `AgentEvent` and is not
// journalled (§2a of the C4 parity plan), so the projection prices
// the call with the same estimator the live path uses as its floor.
- // The token counts are exact; `cost_usd` is a catalog estimate, and
- // adds nothing for a model the catalog does not price.
+ // The token counts are exact; `cost_usd` is an estimate.
+ // An unpriced model adds nothing rather than a placeholder rate.
- state.cost_usd += crate::agent::cost::estimate_known_call_cost_usd(
+ state.cost_usd += crate::agent::cost::estimate_call_cost_usd(
&state.model,
- &crate::inference::provider::BilledUsage::from_counts(usage.input_tokens, usage.output_tokens).with_cached_input_tokens(usage.cache_read_tokens).with_cache_creation_tokens(usage.cache_creation_tokens).with_reasoning_tokens(usage.reasoning_tokens),
+ &crate::inference::provider::BilledUsage::from_counts(
+ usage.input_tokens,
+ usage.output_tokens,
+ )
+ .with_cached_input_tokens(usage.cache_read_tokens)
+ .with_cache_creation_tokens(usage.cache_creation_tokens)
+ .with_reasoning_tokens(usage.reasoning_tokens),
)
.unwrap_or(0.0);
state.input_tokens += usage.input_tokens;
diff --cc crates/openhuman-core/src/agent/session_host/driver.rs
index 35861472b5,3f1c85ed0c..fccb167600
--- a/crates/openhuman-core/src/agent/session_host/driver.rs
+++ b/crates/openhuman-core/src/agent/session_host/driver.rs
@@@ -387,16 -386,27 +386,28 @@@ impl SessionDriver<OpenHumanRunContext
+ repair_usage
.map(|usage| usage.cached_input_tokens)
.unwrap_or_default();
- observed.cost_usd = outcome.charged_amount_usd
- + close
- .as_ref()
- .map(|close| close.usage.charged_amount_usd)
- .unwrap_or_default()
- + repair_usage
- .map(|usage| usage.charged_amount_usd)
- .unwrap_or_default();
+ let mut cost = outcome.cost;
+ if let Some(close) = close.as_ref() {
+ cost.merge(close.usage.cost);
+ }
+ if let Some(repair) = repair_usage {
+ cost.merge(repair.cost);
+ }
+ observed.cost = cost;
+ let loop_last_call = snapshot
+ .lock()
+ .ok()
+ .map(|guard| (guard.last_call_input_tokens, guard.last_call_output_tokens));
+ (
+ observed.last_call_input_tokens,
+ observed.last_call_output_tokens,
+ ) = final_call_tokens(
+ loop_last_call,
+ close.as_ref().map(|close| &close.usage),
+ repair_usage,
+ );
observed.duration = Some(started.elapsed());
+ observed.driver_finished_at = Some(std::time::Instant::now());
observed.tool_outcomes = outcome.tool_outcomes.clone();
observed.hit_cap = outcome.hit_cap;
observed.wrap_up_injected = outcome.wrap_up_injected;
diff --cc crates/openhuman-core/src/agent/subagent_host/ops/graph_tests.rs
index fa18e788c0,e2ede25c3d..97d8be9305
--- a/crates/openhuman-core/src/agent/subagent_host/ops/graph_tests.rs
+++ b/crates/openhuman-core/src/agent/subagent_host/ops/graph_tests.rs
@@@ -9,50 -9,6 +9,53 @@@ use tinyinference_llm::tool::ToolCall
use tinytools::Tool;
use tinytools::ToolResult;
+#[test]
+fn subagent_transcript_keeps_cumulative_spend_separate_from_unknown_last_call() {
+ let workspace = tempfile::tempdir().unwrap();
+ let usage = AggregatedUsage {
+ input_tokens: 120,
+ output_tokens: 30,
+ cached_input_tokens: 40,
- charged_amount_usd: 0.01,
++ cost: crate::agent::cost::CostTally {
++ known_usd: 0.01,
++ source: crate::agent::cost::CostSource::Charged,
++ },
+ };
+ super::transcript::persist_subagent_transcript(
+ workspace.path(),
+ "root__usage",
+ "worker",
+ "task",
+ "mock",
+ "model",
+ &[TranscriptMessage::assistant("done")],
+ &usage,
+ None,
+ 200_000,
+ "test",
+ 2,
+ );
+ let root = crate::agent::session_store::transcript_root(workspace.path());
+ let path = tinyagents_session::transcript::resolve_keyed_transcript_path(&root, "root__usage")
+ .unwrap();
+ let transcript = tinyagents_session::transcript::read_transcript(&path).unwrap();
+ let recorded = &transcript
+ .messages
+ .last()
+ .unwrap()
+ .turn_usage
+ .as_ref()
+ .unwrap()
+ .usage;
+ assert_eq!(recorded.input, 120);
+ assert_eq!(recorded.output, 30);
+ assert_eq!(recorded.cached_input, 40);
+ assert_eq!(recorded.context_window, 200_000);
+ assert_eq!(recorded.cost_usd, 0.01);
+ assert_eq!(recorded.last_call_input, 0);
+ assert_eq!(recorded.last_call_output, 0);
+}
+
fn native_tool_profile() -> &'static ModelProfile {
static PROFILE: std::sync::LazyLock<ModelProfile> = std::sync::LazyLock::new(|| ModelProfile {
provider: Some("subagent-graph-test".to_string()),
diff --cc vendor/tinyagents
index 72be6fae0c,8678404113..3b6ddf1397
--- a/vendor/tinyagents
+++ b/vendor/tinyagents
@@@ -1,1 -1,1 +1,1 @@@
- Subproject commit 72be6fae0c9e52730ba6f9ab943d266612834dda
-Subproject commit 867840411382f9a4eeecc6e621ceac26cf0fc8e7
++Subproject commit 3b6ddf1397b61d95a642b474ce3d59bff645e35d