Skip to content

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

fix(threads): count cached tokens in context usage breakdown

Steven Enamakel36a76d55801f
diff --git a/crates/openhuman-core/src/agent/context_breakdown.rs b/crates/openhuman-core/src/agent/context_breakdown.rs
index 7ed8a997c1..f24d24ed2d 100644
--- a/crates/openhuman-core/src/agent/context_breakdown.rs
+++ b/crates/openhuman-core/src/agent/context_breakdown.rs
@@ -137,10 +137,17 @@ fn history_tokens(context_tokens: usize, fixed_prompt_tokens: usize) -> usize {
context_tokens.saturating_sub(fixed_prompt_tokens)
}
-async fn history_section(thread_id: &str, fixed_prompt_tokens: usize) -> Option<ContextSection> {
- let outcome = crate::threads::ops::token_usage(crate::threads::ops::ThreadTokenUsageRequest {
- thread_id: thread_id.to_string(),
- })
+async fn history_section(
+ ctx: &DispatchCtx,
+ thread_id: &str,
+ fixed_prompt_tokens: usize,
+) -> Option<ContextSection> {
+ let outcome = crate::threads::ops::token_usage(
+ ctx,
+ crate::threads::ops::ThreadTokenUsageRequest {
+ thread_id: thread_id.to_string(),
+ },
+ )
.await
.ok()?;
let usage = outcome.value.data?;
@@ -205,7 +212,7 @@ pub async fn context_breakdown(
.map(str::trim)
.filter(|s| !s.is_empty())
{
- if let Some(history) = history_section(thread_id, fixed_prompt_tokens).await {
+ if let Some(history) = history_section(ctx, thread_id, fixed_prompt_tokens).await {
sections.push(history);
}
}
diff --git a/crates/openhuman-core/src/threads/ops/transcript.rs b/crates/openhuman-core/src/threads/ops/transcript.rs
index 032dfb2c13..94c1395cf9 100644
--- a/crates/openhuman-core/src/threads/ops/transcript.rs
+++ b/crates/openhuman-core/src/threads/ops/transcript.rs
@@ -1,6 +1,7 @@
//! Paginated projection of a thread's settled transcript.
-use super::support::{counts, envelope, workspace_dir};
+use super::support::{counts, envelope, transcript_store};
+use crate::core::runtime::DispatchCtx;
use crate::core::Outcome;
use crate::threads::{ApiEnvelope, PaginationMeta};
@@ -16,23 +17,32 @@ pub struct TranscriptGetRequest {
pub limit: Option<usize>,
}
-/// Project a thread's settled transcript (derived from `session_raw/*.jsonl`)
-/// into typed display items, newest-first paginated. Returns an empty page with
-/// `hasTranscript: false` when the thread has no persisted transcript yet.
+/// Project a thread's settled transcript (read from the session store the
+/// request's tenant wrote it to) into typed display items, newest-first
+/// paginated. Returns an empty page with `hasTranscript: false` when the
+/// thread has no persisted transcript yet.
pub async fn transcript_get(
+ ctx: &DispatchCtx,
request: TranscriptGetRequest,
) -> Result<Outcome<ApiEnvelope<tinyagents_session::transcript::view::TranscriptPage>>, String> {
- let dir = workspace_dir().await?;
- let thread_id = request.thread_id.trim();
+ let thread_id = request.thread_id.trim().to_string();
if thread_id.is_empty() {
return Err("thread_id is required".to_string());
}
- let page = tinyagents_session::transcript::view::get_page(
- &dir,
- thread_id,
- request.cursor.as_deref(),
- request.limit,
- );
+ let store = transcript_store(ctx).await?;
+ let cursor = request.cursor.clone();
+ let limit = request.limit;
+ let page = tokio::task::spawn_blocking(move || {
+ tinyagents_session::transcript::view::get_page_in(
+ store.locator().as_ref(),
+ &thread_id,
+ None,
+ cursor.as_deref(),
+ limit,
+ )
+ })
+ .await
+ .map_err(|e| format!("transcript page task: {e}"))?;
let counts = counts([
("items", page.items.len()),
("total", page.total),
diff --git a/crates/openhuman-core/src/threads/ops/usage.rs b/crates/openhuman-core/src/threads/ops/usage.rs
index 514dbaccec..b74e99b3a4 100644
--- a/crates/openhuman-core/src/threads/ops/usage.rs
+++ b/crates/openhuman-core/src/threads/ops/usage.rs
@@ -1,9 +1,10 @@
//! Aggregated token/cost usage for a thread, re-audited at current pricing.
-use super::support::{counts, envelope, workspace_dir};
+use super::support::{counts, envelope, transcript_store};
+use crate::core::runtime::DispatchCtx;
use crate::core::Outcome;
use crate::threads::ApiEnvelope;
-use tinyagents_session::transcript::spend::thread_spend;
+use tinyagents_session::transcript::spend::thread_spend_in;
/// Request for [`token_usage`]: the thread whose persisted usage to total.
#[derive(Debug, Clone, serde::Deserialize)]
@@ -61,12 +62,20 @@ pub struct SubagentUsageDto {
pub runs: usize,
}
-/// Total a thread's persisted token/cost usage across its root transcripts.
+/// Total a thread's persisted token/cost usage across its root transcripts
+/// and their sub-agents, read from the store the request's tenant wrote them
+/// to.
pub async fn token_usage(
+ ctx: &DispatchCtx,
request: ThreadTokenUsageRequest,
) -> Result<Outcome<ApiEnvelope<ThreadTokenUsageResponse>>, String> {
- let dir = workspace_dir().await?;
- let spend = thread_spend(&dir, &request.thread_id);
+ let store = transcript_store(ctx).await?;
+ let thread_id = request.thread_id.clone();
+ let spend = tokio::task::spawn_blocking(move || {
+ thread_spend_in(store.locator().as_ref(), &thread_id)
+ })
+ .await
+ .map_err(|e| format!("thread usage task: {e}"))?;
if !spend.found_transcript {
return Ok(envelope(
diff --git a/crates/openhuman-core/src/threads/schemas/handlers.rs b/crates/openhuman-core/src/threads/schemas/handlers.rs
index 693b09b447..b16f18aba9 100644
--- a/crates/openhuman-core/src/threads/schemas/handlers.rs
+++ b/crates/openhuman-core/src/threads/schemas/handlers.rs
@@ -174,22 +174,22 @@ pub(super) fn handle_turn_state_clear(
}
pub(super) fn handle_token_usage(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
let p = parse::<ops::ThreadTokenUsageRequest>(params)?;
- to_json(ops::token_usage(p).await?)
+ to_json(ops::token_usage(&ctx, p).await?)
})
}
pub(super) fn handle_transcript_get(
- _ctx: DispatchCtx,
+ ctx: DispatchCtx,
params: Map<String, Value>,
) -> ControllerFuture {
Box::pin(async move {
let p = parse::<ops::TranscriptGetRequest>(params)?;
- to_json(ops::transcript_get(p).await?)
+ to_json(ops::transcript_get(&ctx, p).await?)
})
}