Skip to content

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

refactor(agent): extract journal projection helpers

Steven Enamakel8b6370fbe4df
diff --git a/crates/openhuman-core/src/agent/progress_tracing/journal_projection.rs b/crates/openhuman-core/src/agent/progress_tracing/journal_projection.rs
index c6ae0760cf..dc1939a998 100644
--- a/crates/openhuman-core/src/agent/progress_tracing/journal_projection.rs
+++ b/crates/openhuman-core/src/agent/progress_tracing/journal_projection.rs
@@ -60,6 +60,10 @@ use tinyagents_harness::observability::AgentObservation;
use super::SpanCollector;
use crate::agent::progress::AgentProgress;
+use replay::{json_content_text, turn_outcome_for_failure, user_message_text, Replay};
+
+#[path = "journal_replay.rs"]
+mod replay;
use crate::tools::status::classify;
use tinyagents_harness::observability::trace_export::{TraceContext, TraceSpan};
@@ -98,6 +102,12 @@ struct ReplayState {
/// un-journalled `usage_carry` side-channel, so this is an estimate — see
/// the module header.
cost_usd: f64,
+ /// Model of the most recent `ModelStarted` in any scope: the name for a
+ /// `ModelCompleted` whose own `ModelStarted` is missing from the journal.
+ last_model_any: String,
+ /// Collector steps produced by the current observation that must run
+ /// before its returned progress (see [`Replay`]). Drained per observation.
+ pre: Vec<Replay>,
/// `call_id → requested tool name` for calls the crate answered as an
/// unknown tool. The crate's own `ToolStarted`/`ToolCompleted` pair for the
/// same call id follows; this lets it carry the "unavailable" label and the
@@ -172,6 +182,7 @@ fn observation_to_progress(obs: &AgentObservation, state: &mut ReplayState) -> V
state
.models
.insert(call_id.as_str().to_string(), model.clone());
+ state.last_model_any = model.clone();
match state.active_subagent() {
Some(scope) => vec![AgentProgress::SubagentIterationStarted {
agent_id: scope.agent_id.clone(),
@@ -390,18 +401,61 @@ fn observation_to_progress(obs: &AgentObservation, state: &mut ReplayState) -> V
AgentEvent::ModelCompleted {
call_id,
+ started_at_ms,
usage,
input,
output,
- ..
} => {
- let model = state
- .models
- .get(call_id.as_str())
- .cloned()
- .unwrap_or_default();
let usage = usage.unwrap_or_default();
+ let start = started_at_ms.unwrap_or(obs.ts_ms).min(obs.ts_ms);
+ let model = match state.models.remove(call_id.as_str()) {
+ Some(model) => model,
+ None => {
+ // The harness emits one `ModelStarted` per `ModelCompleted`,
+ // so a completion with no start means the journal lost the
+ // start. Without one the call joined the previous iteration,
+ // shared its start instant and carried no model name (seen
+ // in production as several `llm.` generations starting in
+ // the same millisecond). Open the iteration it belongs to at
+ // the call's own start instead.
+ log::debug!(
+ "[agent-tracing][journal] ModelCompleted without ModelStarted \
+ call_id={} run_id={}; synthesizing its iteration",
+ call_id.as_str(),
+ obs.run_id.as_str()
+ );
+ let iteration = match state.active_subagent_mut() {
+ Some(scope) => {
+ scope.iteration += 1;
+ scope.iteration
+ }
+ None => {
+ state.iteration += 1;
+ state.iteration
+ }
+ };
+ let started = match state.active_subagent() {
+ Some(scope) => AgentProgress::SubagentIterationStarted {
+ agent_id: scope.agent_id.clone(),
+ task_id: scope.task_id.clone(),
+ iteration,
+ max_iterations: state.max_iterations,
+ extended_policy: false,
+ },
+ None => AgentProgress::IterationStarted {
+ iteration,
+ max_iterations: state.max_iterations,
+ },
+ };
+ state.pre.push(Replay::At(started, start));
+ state.last_model_any.clone()
+ }
+ };
let scope = state.active_subagent().cloned();
+ state.pre.push(Replay::CallStart(
+ scope.as_ref().map(|s| s.task_id.clone()),
+ start,
+ ));
let iteration = scope
.as_ref()
.map(|s| s.iteration)
@@ -429,7 +483,11 @@ fn observation_to_progress(obs: &AgentObservation, state: &mut ReplayState) -> V
cost_usd: 0.0,
}];
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 {
@@ -468,10 +526,18 @@ fn observation_to_progress(obs: &AgentObservation, state: &mut ReplayState) -> V
// 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 an estimate.
- state.cost_usd += crate::agent::cost::estimate_call_cost_usd(
+ // An unpriced model adds nothing rather than a placeholder rate.
+ state.cost_usd += crate::agent::cost::estimate_known_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;
state.output_tokens += usage.output_tokens;
state.cached_input_tokens += usage.cache_read_tokens;
@@ -542,8 +608,13 @@ fn observation_to_progress(obs: &AgentObservation, state: &mut ReplayState) -> V
}
}
- AgentEvent::RunFailed { error, .. } => {
+ AgentEvent::RunFailed { error, outcome, .. } => {
let Some(scope) = state.subagents.pop() else {
+ // The top-level run failed: the turn span reports it instead of
+ // closing as an unremarkable, status-less span.
+ state
+ .pre
+ .push(Replay::Outcome(turn_outcome_for_failure(error, outcome.as_ref())));
return Vec::new();
};
vec![AgentProgress::SubagentFailed {
@@ -617,18 +688,6 @@ fn observation_to_progress(obs: &AgentObservation, state: &mut ReplayState) -> V
}
}
-fn json_content_text(value: &serde_json::Value) -> String {
- match value {
- serde_json::Value::String(text) => text.clone(),
- serde_json::Value::Object(map) => map
- .get("content")
- .and_then(serde_json::Value::as_str)
- .map(str::to_string)
- .unwrap_or_else(|| value.to_string()),
- _ => value.to_string(),
- }
-}
-
/// Projects a run's journalled `observations` into trace spans by replaying
/// them into [`AgentProgress`] and folding through a fresh [`SpanCollector`],
/// stamped with each observation's journal timestamp (`ts_ms`).
@@ -646,7 +705,17 @@ pub(crate) fn spans_from_observations(
let mut last_ts = 0;
for obs in observations {
last_ts = obs.ts_ms;
- for progress in observation_to_progress(obs, &mut state) {
+ let progress = observation_to_progress(obs, &mut state);
+ for step in std::mem::take(&mut state.pre) {
+ match step {
+ Replay::At(event, at) => collector.record(&event, at),
+ Replay::CallStart(task_id, at) => {
+ collector.set_next_call_start(task_id.as_deref(), at)
+ }
+ Replay::Outcome(outcome) => collector.apply_turn_outcome(outcome, obs.ts_ms),
+ }
+ }
+ for progress in progress {
collector.record(&progress, obs.ts_ms);
}
}
diff --git a/crates/openhuman-core/src/security/approval/gate_ttl_and_triage_tests.rs b/crates/openhuman-core/src/security/approval/gate_ttl_and_triage_tests.rs
index ef10226c19..3fd9f9f469 100644
--- a/crates/openhuman-core/src/security/approval/gate_ttl_and_triage_tests.rs
+++ b/crates/openhuman-core/src/security/approval/gate_ttl_and_triage_tests.rs
@@ -313,7 +313,7 @@ mod resolve_park_ttl_tests {
fn default_park_keeps_the_full_ttl() {
let default_ttl = DEFAULT_APPROVAL_TTL;
assert_eq!(
- ApprovalGate::resolve_park_ttl(default_ttl, false),
+ ApprovalGate::resolve_park_ttl(default_ttl, false, false),
default_ttl,
"a plain park (no copilot stream) must not be clamped"
);
@@ -323,7 +323,7 @@ mod resolve_park_ttl_tests {
fn copilot_stream_shortens_a_default_ten_minute_park() {
let default_ttl = DEFAULT_APPROVAL_TTL;
assert_eq!(
- ApprovalGate::resolve_park_ttl(default_ttl, true),
+ ApprovalGate::resolve_park_ttl(default_ttl, true, false),
COPILOT_APPROVAL_TTL,
"a flows_build copilot-streaming park must clamp to COPILOT_APPROVAL_TTL"
);
@@ -341,7 +341,7 @@ mod resolve_park_ttl_tests {
// already shorter than either clamp).
let short_ttl = Duration::from_secs(60);
assert_eq!(
- ApprovalGate::resolve_park_ttl(short_ttl, true),
+ ApprovalGate::resolve_park_ttl(short_ttl, true, false),
short_ttl,
"copilot clamp must not extend a boot-time TTL that is already shorter"
);