Skip to content

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

fix(embed): prefer buyer charges and retry truncation aliases

Steven Enamakelb6bbbc2e8b88
diff --git a/crates/openhuman-embed/ROUTING.md b/crates/openhuman-embed/ROUTING.md
index 9073208a7f..5701023cbc 100644
--- a/crates/openhuman-embed/ROUTING.md
+++ b/crates/openhuman-embed/ROUTING.md
@@ -32,7 +32,7 @@ truncation growth; omitting the builder inherits the request cap. Options are
replaced before `unpinned()` removes the provider routing object. Rung debug
output omits option values. Each fallback retries from its own initial cap.
-A `length` finish
+A case-insensitive `length` or `max_tokens` finish
reason retries the same rung at doubled caps, bounded by both the retry count
and absolute ceiling; 1024 tokens with the example policy tries 1024, 2048,
4096. A missing cap never creates an implicit token budget. At the ceiling,
@@ -47,8 +47,11 @@ gateway route choose its serving provider without changing the requested
model. Adding a rung after an unpinned rung fails before any dispatch.
`response.usage` describes the winning call. `attempts` records every call,
-including truncated responses. `total_usage` sums reported tokens and costs;
-its cost is unknown (`None`) when any attempt's cost was not reported. The
+including truncated responses. Buyer `usage.buyer_cost_micro` charges take
+precedence over relayed `usage.cost`, then normalized `charged_amount`. The
+selected amount must be finite and nonnegative; invalid selected charges stay
+unknown. `total_usage` sums reported tokens and costs;
+its cost is unknown (`None`) when any attempt's cost was missing or invalid. The
ladder error retains this accounting and the last typed error. Completer
observers run for each call, so hosts can meter failures independently.
diff --git a/crates/openhuman-embed/src/complete.rs b/crates/openhuman-embed/src/complete.rs
index 9f5140d0a0..5cbd6a7953 100644
--- a/crates/openhuman-embed/src/complete.rs
+++ b/crates/openhuman-embed/src/complete.rs
@@ -271,8 +271,9 @@ pub struct CompletionUsage {
pub cached_tokens: u64,
/// Reasoning tokens, when the provider reports them.
pub reasoning_tokens: u64,
- /// What the provider says it charged, in USD, when it says. Never a local
- /// price estimate: a host that wants one owns that table.
+ /// Selected provider charge in USD: buyer microcharge, raw gateway cost,
+ /// then normalized charge. Missing or invalid selected amounts stay unknown.
+ /// Never a local price estimate: a host that wants one owns that table.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cost_usd: Option<f64>,
}
@@ -321,25 +322,39 @@ impl CompletionResponse {
.and_then(|raw| raw.get("model"))
.and_then(Value::as_str)
.map(str::to_string);
- let raw_cost = raw
+ // A relay may report its own upstream `cost: 0` while the buyer pays
+ // `buyer_cost_micro`. That actual bill precedes normalized estimates.
+ let cost_usd = raw
.as_ref()
- .and_then(|raw| raw.pointer("/usage/cost"))
- .and_then(Value::as_f64);
+ .and_then(|raw| raw.pointer("/usage/buyer_cost_micro"))
+ .and_then(Value::as_f64)
+ .map(|micro| micro / 1_000_000.0)
+ .or_else(|| {
+ raw.as_ref()
+ .and_then(|raw| raw.pointer("/usage/cost"))
+ .and_then(Value::as_f64)
+ })
+ .or_else(|| {
+ response
+ .usage
+ .as_ref()
+ .and_then(|usage| usage.charged_amount)
+ .map(|amount| amount.micros as f64 / 1_000_000.0)
+ })
+ // Invalid authoritative charges stay unknown, rather than being
+ // replaced by a lower-priority estimate or crediting the budget.
+ .filter(|cost| cost.is_finite() && *cost >= 0.0);
let usage = match response.usage {
Some(usage) => Some(CompletionUsage {
input_tokens: usage.input_tokens,
output_tokens: usage.output_tokens,
cached_tokens: usage.cache_read_tokens,
reasoning_tokens: usage.reasoning_tokens,
- cost_usd: usage
- .charged_amount
- .map(|amount| amount.micros as f64 / 1_000_000.0)
- .or(raw_cost),
+ cost_usd,
}),
- // Some gateways report `usage.cost` in the raw body without the
- // typed usage block. Keep the provider's cost rather than dropping
- // it; the token counts are unknown and stay zero.
- None => raw_cost.map(|cost| CompletionUsage {
+ // Raw gateway charges can survive without a typed usage block;
+ // retain them while unknown token counts stay zero.
+ None => cost_usd.map(|cost| CompletionUsage {
cost_usd: Some(cost),
..CompletionUsage::default()
}),
@@ -634,3 +649,7 @@ impl Completer {
#[cfg(test)]
#[path = "complete_tests.rs"]
mod tests;
+
+#[cfg(test)]
+#[path = "../tests/unit/completion_cost.rs"]
+mod cost_tests;
diff --git a/crates/openhuman-embed/src/routing.rs b/crates/openhuman-embed/src/routing.rs
index f2514bdb60..0344090aa7 100644
--- a/crates/openhuman-embed/src/routing.rs
+++ b/crates/openhuman-embed/src/routing.rs
@@ -252,7 +252,10 @@ impl CompletionLadder {
failed: true,
},
};
- let truncated = attempt.finish_reason.as_deref() == Some("length");
+ let truncated = attempt.finish_reason.as_deref().is_some_and(|reason| {
+ reason.eq_ignore_ascii_case("length")
+ || reason.eq_ignore_ascii_case("max_tokens")
+ });
attempts.push(attempt);
match response {
Ok(response) if !truncated => {
diff --git a/crates/openhuman-embed/tests/completion_routing.rs b/crates/openhuman-embed/tests/completion_routing.rs
index 2d92246469..3a6b3b2d38 100644
--- a/crates/openhuman-embed/tests/completion_routing.rs
+++ b/crates/openhuman-embed/tests/completion_routing.rs
@@ -36,7 +36,7 @@ fn rung(server: &MockServer, model: &str) -> CompletionRung {
}
#[tokio::test]
async fn truncation_doubles_the_cap_before_ordered_unpinned_fallback() {
- let first = scripted(vec![answer("first-actual", "length", 0.01)]).await;
+ let first = scripted(vec![answer("first-actual", "LeNgTh", 0.01)]).await;
let last = scripted(vec![answer("last-actual", "stop", 0.02)]).await;
let outcome = CompletionLadder::new(rung(&first,"first"))
.fallback(rung(&last,"last").unpinned())
@@ -249,3 +249,36 @@ async fn unpinned_rung_removes_its_own_pin_and_can_explicitly_clear_the_cap() {
assert!(body.get("max_tokens").is_none());
assert_eq!(body["reasoning"]["effort"], "high");
}
+
+#[tokio::test]
+async fn uppercase_max_tokens_retries_the_same_rung_and_counts_buyer_charges() {
+ let mut truncated = answer("actual", "MAX_TOKENS", 0.0);
+ truncated["usage"]["buyer_cost_micro"] = json!(3);
+ let mut complete = answer("actual", "stop", 0.0);
+ complete["usage"]["buyer_cost_micro"] = json!(4);
+ let provider = scripted(vec![truncated, complete]).await;
+ let fallback = scripted(vec![answer("unused", "stop", 0.5)]).await;
+ let outcome = CompletionLadder::new(rung(&provider, "primary"))
+ .fallback(rung(&fallback, "fallback"))
+ .truncation_retry(TruncationRetry::new(1, 64))
+ .complete(
+ CompletionRequest::new("ignored", vec![ChatMessage::user("review")]).max_tokens(16),
+ )
+ .await
+ .unwrap();
+ assert_eq!(outcome.attempts.len(), 2);
+ assert_eq!(
+ outcome.attempts[0].finish_reason.as_deref(),
+ Some("MAX_TOKENS")
+ );
+ assert_eq!(outcome.attempts[1].max_tokens, Some(32));
+ assert_eq!(outcome.response.usage.unwrap().cost_usd, Some(0.000004));
+ assert!((outcome.total_usage.unwrap().cost_usd.unwrap() - 0.000007).abs() < 1e-12);
+ assert!(fallback.received_requests().await.unwrap().is_empty());
+ let requests = provider.received_requests().await.unwrap();
+ assert_eq!(requests.len(), 2);
+ for (request, cap) in requests.iter().zip([16, 32]) {
+ let body: Value = serde_json::from_slice(&request.body).unwrap();
+ assert_eq!(body["max_tokens"], cap);
+ }
+}
diff --git a/crates/openhuman-embed/tests/unit/completion_cost.rs b/crates/openhuman-embed/tests/unit/completion_cost.rs
new file mode 100644
index 0000000000..3324bc341f
--- /dev/null
+++ b/crates/openhuman-embed/tests/unit/completion_cost.rs
@@ -0,0 +1,69 @@
+//! Provider charge selection at the private wire-conversion boundary.
+use super::*;
+use serde_json::json;
+use tinyinference_llm::usage::{ChargedAmount, Usage};
+
+fn cost(raw: Option<Value>, charged_micros: Option<i64>) -> Option<f64> {
+ let mut response = ModelResponse::assistant("ok");
+ response.raw = raw;
+ response.usage = Some(Usage {
+ charged_amount: charged_micros.map(ChargedAmount::usd_micros),
+ ..Usage::default()
+ });
+ CompletionResponse::from_wire(response, None)
+ .usage
+ .unwrap()
+ .cost_usd
+}
+
+#[test]
+fn buyer_microcharge_overrides_relayed_cost_and_normalized_estimate() {
+ assert_eq!(
+ cost(
+ Some(json!({"usage":{"buyer_cost_micro":3,"cost":0,"is_byok":true}})),
+ Some(900_000)
+ ),
+ Some(0.000003)
+ );
+ assert_eq!(
+ cost(
+ Some(json!({"usage":{"buyer_cost_micro":0,"cost":0.5}})),
+ Some(900_000)
+ ),
+ Some(0.0)
+ );
+}
+
+#[test]
+fn gateway_cost_precedes_typed_charge_and_typed_charge_remains_a_fallback() {
+ assert_eq!(
+ cost(Some(json!({"usage":{"cost":0.125}})), Some(900_000)),
+ Some(0.125)
+ );
+ assert_eq!(cost(None, Some(12_345)), Some(0.012345));
+}
+
+#[test]
+fn negative_selected_charges_stay_unknown() {
+ assert_eq!(
+ cost(
+ Some(json!({"usage":{"buyer_cost_micro":-1,"cost":0.5}})),
+ Some(900_000)
+ ),
+ None
+ );
+ assert_eq!(
+ cost(Some(json!({"usage":{"cost":-0.5}})), Some(900_000)),
+ None
+ );
+ assert_eq!(cost(None, Some(-1)), None);
+}
+
+#[test]
+fn buyer_charge_survives_without_normalized_token_usage() {
+ let mut response = ModelResponse::assistant("ok");
+ response.raw = Some(json!({"usage":{"buyer_cost_micro":7}}));
+ let usage = CompletionResponse::from_wire(response, None).usage.unwrap();
+ assert_eq!(usage.cost_usd, Some(0.000007));
+ assert_eq!(usage.input_tokens, 0);
+}
diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md
index 0dd3d3d6e0..976e7177ff 100644
--- a/docs/TEST-COVERAGE-MATRIX.md
+++ b/docs/TEST-COVERAGE-MATRIX.md
@@ -662,8 +662,7 @@ The thread JSONL store moved to `tinyagents_session::threads` (`vendor/tinyagent
| 16.1.12 | API-key credential for library mode | RU+RI | `crates/openhuman-core/src/security/credentials/api_key_tests.rs`, `crates/openhuman-embed/tests/runtime_agents.rs` | ✅ | Key stored as an `api-key` auth profile; wins over an expired session; managed inference sends it as a bearer with no `x-api-key`; auth state reports `credential = "api-key"` |
| 16.1.14 | Host-backed read-only repository toolset | RI | `crates/openhuman-embed/tests/repository_tools.rs`, `crates/openhuman-embed/tests/repository_host_only.rs` | ✅ | Validated tree/range/search/symbol/git queries delegate only to the host; mandatory redaction, fenced bounded output, sanitized failures, and real HostOnly + readonly + untrusted-input refusal of shell/write/network. |
| 16.1.15 | Strict structured output and bounded repair | RI | `crates/openhuman-embed/tests/structured_validation.rs`, `crates/openhuman-embed/tests/structured_turns.rs` | ✅ | Wrong types and numeric combinators refused, invalid/external schemas make no call, repair bounded with usage, terminal length rejected even for complete JSON. |
-| 16.1.16 | Explicit routing ladders and required exploration | RI | `crates/openhuman-embed/tests/completion_routing.rs`, `crates/openhuman-embed/tests/tool_required_routing.rs`, `crates/openhuman-embed/tests/structured_turns.rs` | ✅ | Ordered fallbacks, per-rung option/cap overrides, bounded truncation retries, unpinned terminal provider selection, image/options preservation, accumulated reported costs, actual answering model and refusal of schema-valid output before successful tool execution |
-
+| 16.1.16 | Explicit routing ladders and required exploration | RI | `crates/openhuman-embed/tests/completion_routing.rs`, `crates/openhuman-embed/tests/tool_required_routing.rs`, `crates/openhuman-embed/tests/structured_turns.rs`, `crates/openhuman-embed/tests/unit/completion_cost.rs` | ✅ | Ordered fallbacks, per-rung option/cap overrides, bounded case-insensitive length/max_tokens truncation retries, unpinned terminal provider selection, image/options preservation, accumulated buyer-first reported costs with invalid-charge guards, actual answering model and refusal of schema-valid output before successful tool execution |
| 16.1.19 | Pinned standalone Embed source consumer | Script+RI | `scripts/__tests__/embed-consumer-bootstrap.test.mjs` | ✅ | Exact SHA verification, inherited workspace edition, generated active patches, stable locked offline builds with optional Embed enabled/disabled, default dependency tree without HTTP, no untracked secrets or Git metadata, refused malformed/escaping patches and existing destinations |
| 16.1.17 | Enforced shared turn/run budgets | RU+RI | `crates/openhuman-embed/tests/budget_fanout.rs`, `vendor/tinyagents/vendor/tinyinference/crates/tinyinference-llm/src/model/budget_tests.rs` | ✅ | Atomic parent/child reservations, physical provider admission, conservative unknown spend, cancellation and output cap |
| 16.1.18 | Ordered bounded fanout | RI | `crates/openhuman-embed/tests/budget_fanout.rs` | ✅ | Input-order results, per-branch and child error isolation, branch ceilings, shared-budget concurrent refusal and empty fanout |