Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)

Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
  nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 12:37:52 +01:00
parent e37a0deba9
commit 7c1c6dfa8d
10306 changed files with 748026 additions and 748088 deletions

View File

@@ -0,0 +1,814 @@
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use akode_protocol::protocol::CollabAgentInteractionBeginEvent;
use akode_protocol::protocol::CollabAgentInteractionEndEvent;
use akode_protocol::protocol::CollabAgentSpawnEndEvent;
use akode_protocol::protocol::CollabCloseBeginEvent;
use akode_protocol::protocol::CollabCloseEndEvent;
use akode_protocol::protocol::InterAgentCommunication;
use akode_protocol::protocol::SubAgentActivityEvent;
use akode_protocol::protocol::SubAgentActivityKind;
use serde::Deserialize;
use serde_json::Value;
use super::super::TraceReducer;
use crate::model::ConversationItem;
use crate::model::ConversationItemKind;
use crate::model::ConversationPart;
use crate::model::ConversationRole;
use crate::model::InteractionEdge;
use crate::model::InteractionEdgeKind;
use crate::model::ToolCallKind;
use crate::model::TraceAnchor;
use crate::payload::RawPayloadRef;
/// Agent delivery edge waiting for the recipient-side conversation item.
///
/// Multi-agent v2 records the sender tool before the target thread necessarily
/// includes the delivered mailbox message in a model-visible request. The edge
/// stays pending so it can target that exact conversation item when possible.
pub(in crate::reducer) struct PendingAgentInteractionEdge {
pub(in crate::reducer) edge_id: String,
pub(in crate::reducer) kind: InteractionEdgeKind,
pub(in crate::reducer) source: TraceAnchor,
pub(in crate::reducer) target_thread_id: String,
pub(in crate::reducer) message_author: String,
pub(in crate::reducer) message_content: String,
/// Spawn-only fallback for children that fail before their task message is model-visible.
pub(in crate::reducer) unresolved_spawn_thread_id: Option<String>,
pub(in crate::reducer) started_at_unix_ms: i64,
pub(in crate::reducer) ended_at_unix_ms: Option<i64>,
pub(in crate::reducer) carried_raw_payload_ids: Vec<String>,
}
/// Typed reducer input for a multi-agent v2 child completion notification.
///
/// Child results are observed outside the normal tool lifecycle, but they still
/// carry a parent-thread notification. This wrapper keeps the dispatcher from
/// passing a positional bundle of thread and turn ids.
pub(in crate::reducer) struct ObservedAgentResultEdge {
pub(in crate::reducer) wall_time_unix_ms: i64,
pub(in crate::reducer) edge_id: String,
pub(in crate::reducer) child_thread_id: String,
pub(in crate::reducer) child_codex_turn_id: String,
pub(in crate::reducer) parent_thread_id: String,
pub(in crate::reducer) message: String,
pub(in crate::reducer) carried_payload: Option<RawPayloadRef>,
}
#[derive(Deserialize)]
struct AgentMessageInvocationArgs {
message: String,
}
/// Builds the stable edge id for the spawn relationship between two threads.
pub(in crate::reducer) fn spawn_edge_id(parent_thread_id: &str, child_thread_id: &str) -> String {
format!("edge:spawn:{parent_thread_id}:{child_thread_id}")
}
impl TraceReducer {
/// Starts a multi-agent edge from a runtime begin payload, when the tool kind supports one.
pub(super) fn start_agent_interaction_from_runtime(
&mut self,
tool_call_id: &str,
runtime_payload: &RawPayloadRef,
) -> Result<()> {
let kind = self
.rollout
.tool_calls
.get(tool_call_id)
.with_context(|| format!("agent edge referenced unknown tool call {tool_call_id}"))?
.kind
.clone();
match kind {
ToolCallKind::AssignAgentTask => {
let payload: CollabAgentInteractionBeginEvent =
serde_json::from_value(self.read_payload_json(runtime_payload)?)?;
self.queue_message_agent_interaction(
tool_call_id,
InteractionEdgeKind::AssignAgentTask,
payload.receiver_thread_id.to_string(),
payload.prompt,
/*ended_at_unix_ms*/ None,
)
}
ToolCallKind::SendMessage => {
let payload: CollabAgentInteractionBeginEvent =
serde_json::from_value(self.read_payload_json(runtime_payload)?)?;
self.queue_message_agent_interaction(
tool_call_id,
InteractionEdgeKind::SendMessage,
payload.receiver_thread_id.to_string(),
payload.prompt,
/*ended_at_unix_ms*/ None,
)
}
ToolCallKind::CloseAgent => {
let payload: CollabCloseBeginEvent =
serde_json::from_value(self.read_payload_json(runtime_payload)?)?;
self.upsert_close_agent_interaction(
tool_call_id,
payload.receiver_thread_id.to_string(),
/*ended_at_unix_ms*/ None,
)
}
ToolCallKind::ExecCommand
| ToolCallKind::WriteStdin
| ToolCallKind::ApplyPatch
| ToolCallKind::Mcp { .. }
| ToolCallKind::Web
| ToolCallKind::ImageGeneration
| ToolCallKind::SpawnAgent
| ToolCallKind::WaitAgent
| ToolCallKind::Other { .. } => Ok(()),
}
}
/// Ends or enriches a multi-agent edge from a runtime end payload.
pub(super) fn end_agent_interaction_from_runtime(
&mut self,
wall_time_unix_ms: i64,
tool_call_id: &str,
runtime_payload: &RawPayloadRef,
) -> Result<()> {
let kind = self.rollout.tool_calls[tool_call_id].kind.clone();
// MCP results are opaque evidence; they cannot describe agent interactions.
if matches!(kind, ToolCallKind::Mcp { .. }) {
return Ok(());
}
let runtime_payload_json = self.read_payload_json(runtime_payload)?;
if runtime_payload_json.get("agent_thread_id").is_some() {
let payload: SubAgentActivityEvent = serde_json::from_value(runtime_payload_json)?;
return self.end_sub_agent_activity(wall_time_unix_ms, tool_call_id, &kind, &payload);
}
match kind {
ToolCallKind::SpawnAgent => {
let payload: CollabAgentSpawnEndEvent =
serde_json::from_value(runtime_payload_json)?;
self.end_spawn_agent_interaction(wall_time_unix_ms, tool_call_id, &payload)
}
ToolCallKind::AssignAgentTask => {
let payload: CollabAgentInteractionEndEvent =
serde_json::from_value(runtime_payload_json)?;
self.end_message_agent_interaction(
wall_time_unix_ms,
tool_call_id,
InteractionEdgeKind::AssignAgentTask,
&payload,
)
}
ToolCallKind::SendMessage => {
let payload: CollabAgentInteractionEndEvent =
serde_json::from_value(runtime_payload_json)?;
self.end_message_agent_interaction(
wall_time_unix_ms,
tool_call_id,
InteractionEdgeKind::SendMessage,
&payload,
)
}
ToolCallKind::CloseAgent => {
let payload: CollabCloseEndEvent = serde_json::from_value(runtime_payload_json)?;
self.upsert_close_agent_interaction(
tool_call_id,
payload.receiver_thread_id.to_string(),
Some(wall_time_unix_ms),
)
}
ToolCallKind::ExecCommand
| ToolCallKind::WriteStdin
| ToolCallKind::ApplyPatch
| ToolCallKind::Mcp { .. }
| ToolCallKind::Web
| ToolCallKind::ImageGeneration
| ToolCallKind::WaitAgent
| ToolCallKind::Other { .. } => Ok(()),
}
}
fn end_sub_agent_activity(
&mut self,
wall_time_unix_ms: i64,
tool_call_id: &str,
tool_kind: &ToolCallKind,
payload: &SubAgentActivityEvent,
) -> Result<()> {
let target_thread_id = payload.agent_thread_id.to_string();
match (tool_kind, &payload.kind) {
(ToolCallKind::SpawnAgent, SubAgentActivityKind::Started) => {
let parent_thread_id = self
.rollout
.tool_calls
.get(tool_call_id)
.with_context(|| {
format!("agent activity referenced unknown tool call {tool_call_id}")
})?
.thread_id
.clone();
self.queue_sub_agent_activity_message_edge(
wall_time_unix_ms,
tool_call_id,
spawn_edge_id(&parent_thread_id, &target_thread_id),
InteractionEdgeKind::SpawnAgent,
target_thread_id.clone(),
Some(target_thread_id),
)
}
(ToolCallKind::AssignAgentTask, SubAgentActivityKind::Interacted) => self
.queue_sub_agent_activity_message_edge(
wall_time_unix_ms,
tool_call_id,
tool_edge_id(tool_call_id),
InteractionEdgeKind::AssignAgentTask,
target_thread_id,
/*unresolved_spawn_thread_id*/ None,
),
(ToolCallKind::SendMessage, SubAgentActivityKind::Interacted) => self
.queue_sub_agent_activity_message_edge(
wall_time_unix_ms,
tool_call_id,
tool_edge_id(tool_call_id),
InteractionEdgeKind::SendMessage,
target_thread_id,
/*unresolved_spawn_thread_id*/ None,
),
(ToolCallKind::CloseAgent, SubAgentActivityKind::Interrupted) => self
.upsert_close_agent_interaction(
tool_call_id,
target_thread_id,
Some(wall_time_unix_ms),
),
(_, SubAgentActivityKind::Completed) => Ok(()),
_ => bail!(
"sub-agent activity {:?} does not match tool call kind {tool_kind:?}",
payload.kind
),
}
}
fn queue_sub_agent_activity_message_edge(
&mut self,
wall_time_unix_ms: i64,
tool_call_id: &str,
edge_id: String,
edge_kind: InteractionEdgeKind,
target_thread_id: String,
unresolved_spawn_thread_id: Option<String>,
) -> Result<()> {
let tool_call = self.rollout.tool_calls.get(tool_call_id).with_context(|| {
format!("agent activity referenced unknown tool call {tool_call_id}")
})?;
let started_at_unix_ms = tool_call.execution.started_at_unix_ms;
let message_author = self.agent_path_for_thread(&tool_call.thread_id)?;
let message_content = self.agent_message_content_from_invocation(tool_call_id)?;
let carried_raw_payload_ids = self.agent_tool_payload_ids(tool_call_id)?;
self.queue_or_resolve_agent_interaction_edge(PendingAgentInteractionEdge {
edge_id,
kind: edge_kind,
source: TraceAnchor::ToolCall {
tool_call_id: tool_call_id.to_string(),
},
target_thread_id,
message_author,
message_content,
unresolved_spawn_thread_id,
started_at_unix_ms,
ended_at_unix_ms: Some(wall_time_unix_ms),
carried_raw_payload_ids,
})
}
fn agent_message_content_from_invocation(&self, tool_call_id: &str) -> Result<String> {
let tool_call = self.rollout.tool_calls.get(tool_call_id).with_context(|| {
format!("agent activity referenced unknown tool call {tool_call_id}")
})?;
let invocation_payload_id = tool_call
.raw_invocation_payload_id
.as_deref()
.with_context(|| {
format!("agent activity tool call {tool_call_id} missing invocation payload")
})?;
let invocation_payload = self
.rollout
.raw_payloads
.get(invocation_payload_id)
.with_context(|| {
format!(
"agent activity tool call {tool_call_id} referenced missing invocation payload {invocation_payload_id}"
)
})?;
let invocation = self.read_payload_json(invocation_payload)?;
let arguments = invocation
.get("payload")
.and_then(|payload| payload.get("arguments"))
.and_then(Value::as_str)
.with_context(|| {
format!("agent activity tool call {tool_call_id} missing function arguments")
})?;
let args: AgentMessageInvocationArgs = serde_json::from_str(arguments)
.with_context(|| format!("parse agent activity tool call {tool_call_id} arguments"))?;
Ok(args.message)
}
/// Adds the canonical tool result payload to an already reduced multi-agent edge.
pub(super) fn attach_agent_interaction_tool_result(
&mut self,
tool_call_id: &str,
result_payload: Option<&RawPayloadRef>,
) -> Result<()> {
let Some(result_payload) = result_payload else {
return Ok(());
};
if let Some(edge) = self
.rollout
.interaction_edges
.values_mut()
.find(|edge| tool_call_source_matches(&edge.source, tool_call_id))
{
push_unique(
&mut edge.carried_raw_payload_ids,
&result_payload.raw_payload_id,
);
return Ok(());
}
// Agent delivery edges intentionally wait for the recipient-side
// conversation item. Tool end can arrive before that item is
// reduced, so preserve the response payload on the pending edge rather
// than dropping evidence until the delivery materializes.
if let Some(pending) = self
.pending_agent_interaction_edges
.iter_mut()
.find(|pending| tool_call_source_matches(&pending.source, tool_call_id))
{
push_unique(
&mut pending.carried_raw_payload_ids,
&result_payload.raw_payload_id,
);
}
Ok(())
}
fn end_spawn_agent_interaction(
&mut self,
wall_time_unix_ms: i64,
tool_call_id: &str,
payload: &CollabAgentSpawnEndEvent,
) -> Result<()> {
let Some(child_thread_id) = payload.new_thread_id else {
return Ok(());
};
let tool_call = &self.rollout.tool_calls[tool_call_id];
let child_thread_id = child_thread_id.to_string();
let edge_id = spawn_edge_id(&payload.sender_thread_id.to_string(), &child_thread_id);
let message_author = self.agent_path_for_thread(&tool_call.thread_id)?;
self.queue_or_resolve_agent_interaction_edge(PendingAgentInteractionEdge {
edge_id,
kind: InteractionEdgeKind::SpawnAgent,
source: TraceAnchor::ToolCall {
tool_call_id: tool_call_id.to_string(),
},
target_thread_id: child_thread_id.clone(),
message_author,
message_content: payload.prompt.clone(),
unresolved_spawn_thread_id: Some(child_thread_id),
started_at_unix_ms: tool_call.execution.started_at_unix_ms,
ended_at_unix_ms: Some(wall_time_unix_ms),
carried_raw_payload_ids: self.agent_tool_payload_ids(tool_call_id)?,
})
}
fn end_message_agent_interaction(
&mut self,
wall_time_unix_ms: i64,
tool_call_id: &str,
edge_kind: InteractionEdgeKind,
payload: &CollabAgentInteractionEndEvent,
) -> Result<()> {
self.queue_message_agent_interaction(
tool_call_id,
edge_kind,
payload.receiver_thread_id.to_string(),
payload.prompt.clone(),
Some(wall_time_unix_ms),
)
}
fn queue_message_agent_interaction(
&mut self,
tool_call_id: &str,
kind: InteractionEdgeKind,
target_thread_id: String,
message_content: String,
ended_at_unix_ms: Option<i64>,
) -> Result<()> {
let tool_call = &self.rollout.tool_calls[tool_call_id];
let message_author = self.agent_path_for_thread(&tool_call.thread_id)?;
self.queue_or_resolve_agent_interaction_edge(PendingAgentInteractionEdge {
edge_id: tool_edge_id(tool_call_id),
kind,
source: TraceAnchor::ToolCall {
tool_call_id: tool_call_id.to_string(),
},
target_thread_id,
message_author,
message_content,
unresolved_spawn_thread_id: None,
started_at_unix_ms: tool_call.execution.started_at_unix_ms,
ended_at_unix_ms,
carried_raw_payload_ids: self.agent_tool_payload_ids(tool_call_id)?,
})
}
fn agent_tool_payload_ids(&self, tool_call_id: &str) -> Result<Vec<String>> {
let tool_call =
self.rollout.tool_calls.get(tool_call_id).with_context(|| {
format!("agent edge referenced unknown tool call {tool_call_id}")
})?;
let mut payload_ids = Vec::new();
if let Some(payload_id) = &tool_call.raw_invocation_payload_id {
push_unique(&mut payload_ids, payload_id);
}
for payload_id in &tool_call.raw_runtime_payload_ids {
push_unique(&mut payload_ids, payload_id);
}
if let Some(payload_id) = &tool_call.raw_result_payload_id {
push_unique(&mut payload_ids, payload_id);
}
Ok(payload_ids)
}
fn upsert_close_agent_interaction(
&mut self,
tool_call_id: &str,
target_thread_id: String,
ended_at_unix_ms: Option<i64>,
) -> Result<()> {
if !self.rollout.threads.contains_key(&target_thread_id) {
// A failed close can name a thread that never participated in this
// trace. Keep that evidence on the ToolCall raw payloads rather
// than creating an anchor to a non-existent reduced object.
return Ok(());
}
let started_at_unix_ms = self
.rollout
.tool_calls
.get(tool_call_id)
.with_context(|| format!("close edge referenced unknown tool call {tool_call_id}"))?
.execution
.started_at_unix_ms;
let carried_raw_payload_ids = self.agent_tool_payload_ids(tool_call_id)?;
self.upsert_interaction_edge(InteractionEdge {
edge_id: tool_edge_id(tool_call_id),
kind: InteractionEdgeKind::CloseAgent,
source: TraceAnchor::ToolCall {
tool_call_id: tool_call_id.to_string(),
},
target: TraceAnchor::Thread {
thread_id: target_thread_id,
},
started_at_unix_ms,
ended_at_unix_ms,
carried_item_ids: Vec::new(),
carried_raw_payload_ids,
})
}
/// Queues or resolves the edge from a child completion to its parent notification.
pub(in crate::reducer) fn queue_agent_result_interaction_edge(
&mut self,
observed: ObservedAgentResultEdge,
) -> Result<()> {
let message_author = self.agent_path_for_thread(&observed.child_thread_id)?;
let source = if let Some(source_item_id) = self.latest_assistant_message_item_for_turn(
&observed.child_thread_id,
&observed.child_codex_turn_id,
) {
TraceAnchor::ConversationItem {
item_id: source_item_id,
}
} else {
// Child completion is delivered from AgentStatus, not from transcript
// content. Failed or cancelled children can therefore notify the parent
// without producing a final assistant message. Anchor those edges to
// the child thread so the trace keeps the valid delivery instead of
// inventing a missing conversation item.
TraceAnchor::Thread {
thread_id: observed.child_thread_id,
}
};
self.queue_or_resolve_agent_interaction_edge(PendingAgentInteractionEdge {
edge_id: observed.edge_id,
kind: InteractionEdgeKind::AgentResult,
source,
target_thread_id: observed.parent_thread_id,
message_author,
message_content: observed.message,
unresolved_spawn_thread_id: None,
started_at_unix_ms: observed.wall_time_unix_ms,
ended_at_unix_ms: Some(observed.wall_time_unix_ms),
carried_raw_payload_ids: observed
.carried_payload
.map(|payload| vec![payload.raw_payload_id])
.unwrap_or_default(),
})
}
/// Resolves pending agent edges whose target is the newly reduced conversation item.
pub(in crate::reducer) fn resolve_pending_agent_edges_for_item(
&mut self,
item_id: &str,
) -> Result<()> {
if self.is_interaction_edge_target_item(item_id) {
return Ok(());
}
let Some((thread_id, message_author, message_content)) =
self.inter_agent_message_item(item_id)
else {
return Ok(());
};
let Some(pending_index) = self
.pending_agent_interaction_edges
.iter()
.position(|pending| {
pending.target_thread_id == thread_id
&& pending.message_author == message_author
&& pending.message_content == message_content
})
else {
return Ok(());
};
let pending = self.pending_agent_interaction_edges.remove(pending_index);
self.upsert_agent_interaction_edge_for_item(pending, item_id.to_string())
}
fn queue_or_resolve_agent_interaction_edge(
&mut self,
pending: PendingAgentInteractionEdge,
) -> Result<()> {
if let Some(item_id) = self.find_unlinked_inter_agent_message_item(
&pending.target_thread_id,
&pending.message_author,
&pending.message_content,
) {
return self.upsert_agent_interaction_edge_for_item(pending, item_id);
}
if let Some(existing) = self
.pending_agent_interaction_edges
.iter_mut()
.find(|existing| existing.edge_id == pending.edge_id)
{
if existing.kind != pending.kind
|| existing.source != pending.source
|| existing.target_thread_id != pending.target_thread_id
|| existing.message_author != pending.message_author
|| existing.message_content != pending.message_content
|| existing.unresolved_spawn_thread_id != pending.unresolved_spawn_thread_id
{
bail!(
"pending interaction edge {} was observed with conflicting delivery data",
pending.edge_id
);
}
existing.started_at_unix_ms =
existing.started_at_unix_ms.min(pending.started_at_unix_ms);
existing.ended_at_unix_ms = match (existing.ended_at_unix_ms, pending.ended_at_unix_ms)
{
(Some(existing_ended), Some(pending_ended)) => {
Some(existing_ended.max(pending_ended))
}
(None, ended) | (ended, None) => ended,
};
extend_unique(
&mut existing.carried_raw_payload_ids,
pending.carried_raw_payload_ids,
);
return Ok(());
}
self.pending_agent_interaction_edges.push(pending);
Ok(())
}
/// Materializes unresolved spawn edges that have a valid child-thread fallback target.
pub(in crate::reducer) fn resolve_pending_spawn_edge_fallbacks(&mut self) -> Result<()> {
let pending_edges = std::mem::take(&mut self.pending_agent_interaction_edges);
for pending in pending_edges {
let Some(child_thread_id) = pending.unresolved_spawn_thread_id else {
continue;
};
if pending.kind != InteractionEdgeKind::SpawnAgent {
bail!(
"non-spawn interaction edge {} carried a spawn fallback target",
pending.edge_id
);
}
if !self.rollout.threads.contains_key(&child_thread_id) {
continue;
}
// Spawn normally resolves to the child task message because that is
// where the delegated work first becomes model-visible. A child can
// fail before that transcript item exists, but the spawned thread is
// still real and the spawning tool still created it. Preserve that
// relationship with the thread fallback instead of dropping the edge.
self.upsert_interaction_edge(InteractionEdge {
edge_id: pending.edge_id,
kind: pending.kind,
source: pending.source,
target: TraceAnchor::Thread {
thread_id: child_thread_id,
},
started_at_unix_ms: pending.started_at_unix_ms,
ended_at_unix_ms: pending.ended_at_unix_ms,
carried_item_ids: Vec::new(),
carried_raw_payload_ids: pending.carried_raw_payload_ids,
})?;
}
Ok(())
}
fn upsert_agent_interaction_edge_for_item(
&mut self,
pending: PendingAgentInteractionEdge,
target_item_id: String,
) -> Result<()> {
self.upsert_interaction_edge(InteractionEdge {
edge_id: pending.edge_id,
kind: pending.kind,
source: pending.source,
target: TraceAnchor::ConversationItem {
item_id: target_item_id.clone(),
},
started_at_unix_ms: pending.started_at_unix_ms,
ended_at_unix_ms: pending.ended_at_unix_ms,
carried_item_ids: vec![target_item_id],
carried_raw_payload_ids: pending.carried_raw_payload_ids,
})
}
fn upsert_interaction_edge(&mut self, edge: InteractionEdge) -> Result<()> {
if let Some(existing) = self.rollout.interaction_edges.get_mut(&edge.edge_id) {
if existing.kind != edge.kind
|| existing.source != edge.source
|| existing.target != edge.target
{
bail!(
"interaction edge {} was observed with conflicting endpoints",
edge.edge_id
);
}
existing.started_at_unix_ms = existing.started_at_unix_ms.min(edge.started_at_unix_ms);
existing.ended_at_unix_ms = match (existing.ended_at_unix_ms, edge.ended_at_unix_ms) {
(Some(existing_ended), Some(edge_ended)) => Some(existing_ended.max(edge_ended)),
(None, ended) | (ended, None) => ended,
};
extend_unique(&mut existing.carried_item_ids, edge.carried_item_ids);
extend_unique(
&mut existing.carried_raw_payload_ids,
edge.carried_raw_payload_ids,
);
return Ok(());
}
self.rollout
.interaction_edges
.insert(edge.edge_id.clone(), edge);
Ok(())
}
fn find_unlinked_inter_agent_message_item(
&self,
thread_id: &str,
message_author: &str,
message_content: &str,
) -> Option<String> {
self.rollout
.threads
.get(thread_id)?
.conversation_item_ids
.iter()
.find(|item_id| {
!self.is_interaction_edge_target_item(item_id)
&& self
.inter_agent_message_item(item_id)
.is_some_and(|(_, author, content)| {
author == message_author && content == message_content
})
})
.cloned()
}
fn inter_agent_message_item(&self, item_id: &str) -> Option<(String, String, String)> {
let item = self.rollout.conversation_items.get(item_id)?;
let (author_agent_path, recipient_agent_path, message_content) =
inter_agent_message_fields(item)?;
let thread = self.rollout.threads.get(&item.thread_id)?;
if recipient_agent_path != thread.agent_path {
return None;
}
Some((item.thread_id.clone(), author_agent_path, message_content))
}
fn agent_path_for_thread(&self, thread_id: &str) -> Result<String> {
self.rollout
.threads
.get(thread_id)
.map(|thread| thread.agent_path.clone())
.with_context(|| format!("agent edge referenced unknown thread {thread_id}"))
}
fn is_interaction_edge_target_item(&self, item_id: &str) -> bool {
self.rollout
.interaction_edges
.values()
.any(|edge| matches!(&edge.target, TraceAnchor::ConversationItem { item_id: target } if target == item_id))
}
fn latest_assistant_message_item_for_turn(
&self,
thread_id: &str,
codex_turn_id: &str,
) -> Option<String> {
self.rollout
.conversation_items
.values()
.filter(|item| {
item.thread_id == thread_id
&& item.codex_turn_id.as_deref() == Some(codex_turn_id)
&& item.role == ConversationRole::Assistant
&& item.kind == ConversationItemKind::Message
&& item.agent_message.is_none()
})
.max_by_key(|item| item.first_seen_at_unix_ms)
.map(|item| item.item_id.clone())
}
}
fn extend_unique(items: &mut Vec<String>, new_items: Vec<String>) {
for item in new_items {
if !items.iter().any(|existing| existing == &item) {
items.push(item);
}
}
}
fn tool_edge_id(tool_call_id: &str) -> String {
format!("edge:tool:{tool_call_id}")
}
fn tool_call_source_matches(anchor: &TraceAnchor, tool_call_id: &str) -> bool {
matches!(anchor, TraceAnchor::ToolCall { tool_call_id: source } if source == tool_call_id)
}
fn push_unique(items: &mut Vec<String>, item: &str) {
if !items.iter().any(|existing| existing == item) {
items.push(item.to_string());
}
}
fn inter_agent_message_fields(item: &ConversationItem) -> Option<(String, String, String)> {
if item.role != ConversationRole::Assistant || item.kind != ConversationItemKind::Message {
return None;
}
if let Some(agent_message) = &item.agent_message {
let message_content = match item.body.parts.as_slice() {
[ConversationPart::Text { text }] => text,
[ConversationPart::Encoded { label, value }] if label == "encrypted_content" => value,
[
ConversationPart::Text { .. },
ConversationPart::Encoded { label, value },
] if label == "encrypted_content" => value,
_ => return None,
};
return Some((
agent_message.author.clone(),
agent_message.recipient.clone(),
message_content.clone(),
));
}
// Older traces store multi-agent v2 deliveries as assistant messages whose
// text is serialized `InterAgentCommunication`. Treat only that exact
// transport shape as an edge target; ordinary assistant JSON must not be
// mistaken for cross-thread delivery.
let [ConversationPart::Text { text }] = item.body.parts.as_slice() else {
return None;
};
let communication = serde_json::from_str::<InterAgentCommunication>(text).ok()?;
Some((
communication.author.to_string(),
communication.recipient.to_string(),
communication
.encrypted_content
.unwrap_or(communication.content),
))
}
#[cfg(test)]
#[path = "agents_tests.rs"]
mod tests;

View File

@@ -0,0 +1,994 @@
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
use crate::model::AgentOrigin;
use crate::model::ExecutionStatus;
use crate::model::InteractionEdgeKind;
use crate::model::RolloutStatus;
use crate::model::ToolCallKind;
use crate::model::ToolCallSummary;
use crate::model::TraceAnchor;
use crate::payload::RawPayloadKind;
use crate::payload::RawPayloadRef;
use crate::raw_event::RawToolCallRequester;
use crate::raw_event::RawTraceEventPayload;
use crate::reducer::test_support::append_completed_inference;
use crate::reducer::test_support::append_inference_request;
use crate::reducer::test_support::create_started_agent_writer;
use crate::reducer::test_support::message;
use crate::reducer::test_support::start_agent_turn;
use crate::reducer::test_support::start_thread;
use crate::reducer::test_support::start_turn_for_thread;
use crate::reducer::test_support::trace_context_for_agent;
use crate::reducer::test_support::trace_context_for_thread;
use crate::replay_bundle;
use crate::writer::TraceWriter;
#[test]
fn child_thread_metadata_creates_spawn_origin_without_delivery_edge() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = TraceWriter::create(
temp.path(),
"trace-1".to_string(),
"rollout-1".to_string(),
"019d0000-0000-7000-8000-000000000002".to_string(),
)?;
let metadata = writer.write_json_payload(
RawPayloadKind::SessionMetadata,
&json!({
"nickname": "James",
"agent_role": "explorer",
"task_name": "repo_file_counter",
"model": "gpt-test",
"session_source": {
"subagent": {
"thread_spawn": {
"parent_thread_id": "019d0000-0000-7000-8000-000000000001",
"agent_path": "/root/repo_file_counter",
"agent_nickname": "James",
"agent_role": "explorer"
}
}
}
}),
)?;
writer.append(RawTraceEventPayload::ThreadStarted {
thread_id: "019d0000-0000-7000-8000-000000000002".to_string(),
agent_path: "/root/repo_file_counter".to_string(),
metadata_payload: Some(metadata),
})?;
let replayed = replay_bundle(temp.path())?;
let thread = &replayed.threads["019d0000-0000-7000-8000-000000000002"];
assert_eq!(thread.nickname, Some("James".to_string()));
assert_eq!(thread.default_model, Some("gpt-test".to_string()));
assert_eq!(
thread.origin,
AgentOrigin::Spawned {
parent_thread_id: "019d0000-0000-7000-8000-000000000001".to_string(),
spawn_edge_id: "edge:spawn:019d0000-0000-7000-8000-000000000001:019d0000-0000-7000-8000-000000000002".to_string(),
task_name: "repo_file_counter".to_string(),
agent_role: "explorer".to_string(),
}
);
assert!(
!replayed.interaction_edges.contains_key(
"edge:spawn:019d0000-0000-7000-8000-000000000001:019d0000-0000-7000-8000-000000000002"
),
"spawn metadata identifies the child, but the delivery edge waits for the recipient \
conversation item"
);
Ok(())
}
#[test]
fn spawn_runtime_payload_targets_delivered_child_message() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_agent_writer(&temp)?;
start_agent_turn(&writer, "turn-1")?;
let spawn_payloads = append_spawn_agent_tool_lifecycle(&writer, "turn-1")?;
// Then record the child-side model-visible task message. This is the
// preferred target because it pinpoints where the delegated work entered
// the child timeline.
start_thread(
&writer,
"019d0000-0000-7000-8000-000000000002",
"/root/repo_file_counter",
)?;
start_turn_for_thread(
&writer,
"019d0000-0000-7000-8000-000000000002",
"turn-child-1",
)?;
let delivered = inter_agent_message(
"/root",
"/root/repo_file_counter",
"count",
/*trigger_turn*/ true,
);
append_inference_request(
&writer,
"019d0000-0000-7000-8000-000000000002",
"turn-child-1",
"inference-child-1",
vec![message("assistant", &delivered)],
)?;
let replayed = replay_bundle(temp.path())?;
let edge = &replayed.interaction_edges["edge:spawn:019d0000-0000-7000-8000-000000000001:019d0000-0000-7000-8000-000000000002"];
assert_eq!(edge.kind, InteractionEdgeKind::SpawnAgent);
assert_eq!(
edge.source,
TraceAnchor::ToolCall {
tool_call_id: "call-spawn".to_string()
}
);
let target_item_id = target_conversation_item_id(&edge.target);
assert_eq!(edge.carried_item_ids, vec![target_item_id.clone()]);
assert_eq!(
replayed.conversation_items[target_item_id].thread_id,
"019d0000-0000-7000-8000-000000000002"
);
assert_eq!(
edge.carried_raw_payload_ids,
vec![
spawn_payloads.invocation.raw_payload_id,
spawn_payloads.begin.raw_payload_id,
spawn_payloads.end.raw_payload_id,
spawn_payloads.result.raw_payload_id,
]
);
Ok(())
}
#[test]
fn spawn_runtime_payload_falls_back_to_child_thread_without_delivery_item() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_agent_writer(&temp)?;
start_agent_turn(&writer, "turn-1")?;
let spawn_payloads = append_spawn_agent_tool_lifecycle(&writer, "turn-1")?;
// Deliberately start the child thread without appending an inference
// request containing the inter-agent task message. This reproduces the
// failure path where the child aborts before the reducer can target the
// precise child-side ConversationItem.
start_thread(
&writer,
"019d0000-0000-7000-8000-000000000002",
"/root/repo_file_counter",
)?;
let replayed = replay_bundle(temp.path())?;
let edge = &replayed.interaction_edges["edge:spawn:019d0000-0000-7000-8000-000000000001:019d0000-0000-7000-8000-000000000002"];
assert_eq!(edge.kind, InteractionEdgeKind::SpawnAgent);
assert_eq!(
edge.source,
TraceAnchor::ToolCall {
tool_call_id: "call-spawn".to_string()
}
);
assert_eq!(
edge.target,
TraceAnchor::Thread {
thread_id: "019d0000-0000-7000-8000-000000000002".to_string()
}
);
// No transcript item carried the task, so the fallback edge should not
// claim one. The raw payloads still preserve the tool evidence.
assert!(edge.carried_item_ids.is_empty());
assert_eq!(
edge.carried_raw_payload_ids,
vec![
spawn_payloads.invocation.raw_payload_id,
spawn_payloads.begin.raw_payload_id,
spawn_payloads.end.raw_payload_id,
spawn_payloads.result.raw_payload_id,
]
);
Ok(())
}
#[test]
fn sub_agent_started_activity_creates_spawn_edge() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_agent_writer(&temp)?;
start_agent_turn(&writer, "turn-1")?;
let child_thread_id = "019d0000-0000-7000-8000-000000000002";
let invocation_payload = writer.write_json_payload(
RawPayloadKind::ToolInvocation,
&json!({
"tool_name": "spawn_agent",
"payload": {
"type": "function",
"arguments": "{\"message\":\"review this\",\"task_name\":\"reviewer\"}"
}
}),
)?;
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "call-spawn-v2".to_string(),
model_visible_call_id: Some("call-spawn-v2".to_string()),
code_mode_runtime_tool_id: None,
requester: RawToolCallRequester::Model,
kind: ToolCallKind::SpawnAgent,
summary: ToolCallSummary::Generic {
label: "spawn_agent".to_string(),
input_preview: None,
output_preview: None,
},
invocation_payload: Some(invocation_payload.clone()),
},
)?;
let activity_payload = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"event_id": "call-spawn-v2",
"occurred_at_ms": 1234,
"agent_thread_id": child_thread_id,
"agent_path": "/root/reviewer",
"kind": "started"
}),
)?;
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: "call-spawn-v2".to_string(),
status: ExecutionStatus::Completed,
runtime_payload: activity_payload.clone(),
},
)?;
start_thread(&writer, child_thread_id, "/root/reviewer")?;
start_turn_for_thread(&writer, child_thread_id, "turn-child-1")?;
append_inference_request(
&writer,
child_thread_id,
"turn-child-1",
"inference-child-1",
vec![json!({
"type": "agent_message",
"author": "/root",
"recipient": "/root/reviewer",
"content": [
{
"type": "input_text",
"text": "Message Type: NEW_TASK\nTask name: /root/reviewer\nSender: /root\nPayload:\n"
},
{"type": "encrypted_content", "encrypted_content": "review this"}
]
})],
)?;
let replayed = replay_bundle(temp.path())?;
let edge_id = format!("edge:spawn:019d0000-0000-7000-8000-000000000001:{child_thread_id}");
let edge = &replayed.interaction_edges[&edge_id];
assert_eq!(edge.kind, InteractionEdgeKind::SpawnAgent);
let target_item_id = target_conversation_item_id(&edge.target);
assert_eq!(edge.carried_item_ids, vec![target_item_id.clone()]);
assert_eq!(
replayed.conversation_items[target_item_id].thread_id,
child_thread_id
);
assert_eq!(
edge.carried_raw_payload_ids,
vec![
invocation_payload.raw_payload_id,
activity_payload.raw_payload_id,
]
);
Ok(())
}
#[test]
fn send_message_runtime_payload_targets_delivered_child_message() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_agent_writer(&temp)?;
start_agent_turn(&writer, "turn-1")?;
let invocation_payload = writer.write_json_payload(
RawPayloadKind::ToolInvocation,
&json!({
"tool_name": "send_message",
"payload": {
"type": "function",
"arguments": "{\"target\":\"/root/child\",\"message\":\"hello\"}"
}
}),
)?;
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "call-send".to_string(),
model_visible_call_id: Some("call-send".to_string()),
code_mode_runtime_tool_id: None,
requester: RawToolCallRequester::Model,
kind: ToolCallKind::SendMessage,
summary: ToolCallSummary::Generic {
label: "send_message".to_string(),
input_preview: None,
output_preview: None,
},
invocation_payload: Some(invocation_payload),
},
)?;
let begin_payload = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"call_id": "call-send",
"sender_thread_id": "019d0000-0000-7000-8000-000000000001",
"receiver_thread_id": "019d0000-0000-7000-8000-000000000002",
"prompt": "hello",
"status": "running"
}),
)?;
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallRuntimeStarted {
kind: ToolCallKind::SendMessage,
tool_call_id: "call-send".to_string(),
runtime_payload: begin_payload,
},
)?;
let end_payload = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"call_id": "call-send",
"sender_thread_id": "019d0000-0000-7000-8000-000000000001",
"receiver_thread_id": "019d0000-0000-7000-8000-000000000002",
"prompt": "hello",
"status": "running"
}),
)?;
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: "call-send".to_string(),
status: ExecutionStatus::Completed,
runtime_payload: end_payload,
},
)?;
start_thread(
&writer,
"019d0000-0000-7000-8000-000000000002",
"/root/child",
)?;
start_turn_for_thread(
&writer,
"019d0000-0000-7000-8000-000000000002",
"turn-child-1",
)?;
let delivered =
inter_agent_message("/root", "/root/child", "hello", /*trigger_turn*/ false);
append_inference_request(
&writer,
"019d0000-0000-7000-8000-000000000002",
"turn-child-1",
"inference-child-1",
vec![message("assistant", &delivered)],
)?;
let replayed = replay_bundle(temp.path())?;
let edge = &replayed.interaction_edges["edge:tool:call-send"];
assert_eq!(edge.kind, InteractionEdgeKind::SendMessage);
assert_eq!(
edge.source,
TraceAnchor::ToolCall {
tool_call_id: "call-send".to_string()
}
);
let target_item_id = target_conversation_item_id(&edge.target);
assert_eq!(edge.carried_item_ids, vec![target_item_id.clone()]);
assert_eq!(
replayed.conversation_items[target_item_id].thread_id,
"019d0000-0000-7000-8000-000000000002"
);
assert!(edge.ended_at_unix_ms.is_some());
Ok(())
}
#[test]
fn send_message_activity_targets_delivered_child_message() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_agent_writer(&temp)?;
start_agent_turn(&writer, "turn-1")?;
let child_thread_id = "019d0000-0000-7000-8000-000000000002";
let invocation_payload = writer.write_json_payload(
RawPayloadKind::ToolInvocation,
&json!({
"tool_name": "send_message",
"payload": {
"type": "function",
"arguments": "{\"target\":\"/root/child\",\"message\":\"hello again\"}"
}
}),
)?;
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "call-send-v2".to_string(),
model_visible_call_id: Some("call-send-v2".to_string()),
code_mode_runtime_tool_id: None,
requester: RawToolCallRequester::Model,
kind: ToolCallKind::SendMessage,
summary: ToolCallSummary::Generic {
label: "send_message".to_string(),
input_preview: None,
output_preview: None,
},
invocation_payload: Some(invocation_payload.clone()),
},
)?;
let activity_payload = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"event_id": "call-send-v2",
"occurred_at_ms": 1234,
"agent_thread_id": child_thread_id,
"agent_path": "/root/child",
"kind": "interacted"
}),
)?;
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: "call-send-v2".to_string(),
status: ExecutionStatus::Completed,
runtime_payload: activity_payload.clone(),
},
)?;
start_thread(&writer, child_thread_id, "/root/child")?;
start_turn_for_thread(&writer, child_thread_id, "turn-child-1")?;
let delivered = inter_agent_message(
"/root",
"/root/child",
"hello again",
/*trigger_turn*/ false,
);
append_inference_request(
&writer,
child_thread_id,
"turn-child-1",
"inference-child-1",
vec![message("assistant", &delivered)],
)?;
let replayed = replay_bundle(temp.path())?;
let edge = &replayed.interaction_edges["edge:tool:call-send-v2"];
assert_eq!(edge.kind, InteractionEdgeKind::SendMessage);
let target_item_id = target_conversation_item_id(&edge.target);
assert_eq!(edge.carried_item_ids, vec![target_item_id.clone()]);
assert_eq!(
replayed.conversation_items[target_item_id].thread_id,
child_thread_id
);
assert_eq!(
edge.carried_raw_payload_ids,
vec![
invocation_payload.raw_payload_id,
activity_payload.raw_payload_id,
]
);
Ok(())
}
#[test]
fn followup_activity_targets_delivered_child_message() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_agent_writer(&temp)?;
start_agent_turn(&writer, "turn-1")?;
let child_thread_id = "019d0000-0000-7000-8000-000000000002";
let invocation_payload = writer.write_json_payload(
RawPayloadKind::ToolInvocation,
&json!({
"tool_name": "followup_task",
"payload": {
"type": "function",
"arguments": "{\"target\":\"/root/child\",\"message\":\"continue\"}"
}
}),
)?;
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "call-followup-v2".to_string(),
model_visible_call_id: Some("call-followup-v2".to_string()),
code_mode_runtime_tool_id: None,
requester: RawToolCallRequester::Model,
kind: ToolCallKind::AssignAgentTask,
summary: ToolCallSummary::Generic {
label: "followup_task".to_string(),
input_preview: None,
output_preview: None,
},
invocation_payload: Some(invocation_payload.clone()),
},
)?;
let activity_payload = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"event_id": "call-followup-v2",
"occurred_at_ms": 1234,
"agent_thread_id": child_thread_id,
"agent_path": "/root/child",
"kind": "interacted"
}),
)?;
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: "call-followup-v2".to_string(),
status: ExecutionStatus::Completed,
runtime_payload: activity_payload.clone(),
},
)?;
start_thread(&writer, child_thread_id, "/root/child")?;
start_turn_for_thread(&writer, child_thread_id, "turn-child-1")?;
let delivered = inter_agent_message(
"/root",
"/root/child",
"continue",
/*trigger_turn*/ true,
);
append_inference_request(
&writer,
child_thread_id,
"turn-child-1",
"inference-child-1",
vec![message("assistant", &delivered)],
)?;
let replayed = replay_bundle(temp.path())?;
let edge = &replayed.interaction_edges["edge:tool:call-followup-v2"];
assert_eq!(edge.kind, InteractionEdgeKind::AssignAgentTask);
let target_item_id = target_conversation_item_id(&edge.target);
assert_eq!(edge.carried_item_ids, vec![target_item_id.clone()]);
assert_eq!(
replayed.conversation_items[target_item_id].thread_id,
child_thread_id
);
assert_eq!(
edge.carried_raw_payload_ids,
vec![
invocation_payload.raw_payload_id,
activity_payload.raw_payload_id,
]
);
Ok(())
}
#[test]
fn close_agent_runtime_payload_targets_thread() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_agent_writer(&temp)?;
start_thread(
&writer,
"019d0000-0000-7000-8000-000000000002",
"/root/child",
)?;
start_agent_turn(&writer, "turn-1")?;
let invocation_payload = writer.write_json_payload(
RawPayloadKind::ToolInvocation,
&json!({
"tool_name": "close_agent",
"payload": {
"type": "function",
"arguments": r#"{"target":"/root/child"}"#
}
}),
)?;
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "call-close".to_string(),
model_visible_call_id: Some("call-close".to_string()),
code_mode_runtime_tool_id: None,
requester: RawToolCallRequester::Model,
kind: ToolCallKind::CloseAgent,
summary: ToolCallSummary::Generic {
label: "close_agent".to_string(),
input_preview: None,
output_preview: None,
},
invocation_payload: Some(invocation_payload.clone()),
},
)?;
let begin_payload = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"call_id": "call-close",
"sender_thread_id": "019d0000-0000-7000-8000-000000000001",
"receiver_thread_id": "019d0000-0000-7000-8000-000000000002"
}),
)?;
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallRuntimeStarted {
kind: ToolCallKind::CloseAgent,
tool_call_id: "call-close".to_string(),
runtime_payload: begin_payload.clone(),
},
)?;
let end_payload = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"call_id": "call-close",
"sender_thread_id": "019d0000-0000-7000-8000-000000000001",
"receiver_thread_id": "019d0000-0000-7000-8000-000000000002",
"receiver_agent_nickname": "Scout",
"receiver_agent_role": "explorer",
"status": "running"
}),
)?;
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: "call-close".to_string(),
status: ExecutionStatus::Completed,
runtime_payload: end_payload.clone(),
},
)?;
let result_payload = writer.write_json_payload(
RawPayloadKind::ToolResult,
&json!({"previous_status": "running"}),
)?;
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallEnded {
tool_call_id: "call-close".to_string(),
status: ExecutionStatus::Completed,
result_payload: Some(result_payload.clone()),
},
)?;
writer.append(RawTraceEventPayload::ThreadEnded {
thread_id: "019d0000-0000-7000-8000-000000000002".to_string(),
status: RolloutStatus::Completed,
})?;
let replayed = replay_bundle(temp.path())?;
let edge = &replayed.interaction_edges["edge:tool:call-close"];
assert_eq!(edge.kind, InteractionEdgeKind::CloseAgent);
assert_eq!(
edge.source,
TraceAnchor::ToolCall {
tool_call_id: "call-close".to_string()
}
);
assert_eq!(
edge.target,
TraceAnchor::Thread {
thread_id: "019d0000-0000-7000-8000-000000000002".to_string()
}
);
assert!(edge.carried_item_ids.is_empty());
assert_eq!(
edge.carried_raw_payload_ids,
vec![
invocation_payload.raw_payload_id,
begin_payload.raw_payload_id,
end_payload.raw_payload_id,
result_payload.raw_payload_id,
]
);
assert_eq!(
replayed.threads["019d0000-0000-7000-8000-000000000002"]
.execution
.status,
ExecutionStatus::Completed
);
assert_eq!(replayed.status, RolloutStatus::Running);
Ok(())
}
#[test]
fn agent_result_edge_links_child_result_to_parent_notification() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_agent_writer(&temp)?;
start_thread(
&writer,
"019d0000-0000-7000-8000-000000000002",
"/root/child",
)?;
start_turn_for_thread(
&writer,
"019d0000-0000-7000-8000-000000000002",
"turn-child-1",
)?;
append_completed_inference(
&writer,
"019d0000-0000-7000-8000-000000000002",
"turn-child-1",
"inference-child-1",
vec![message("assistant", "task")],
vec![message("assistant", "done")],
)?;
let notification = "<subagent_notification>{\"agent_path\":\"/root/child\",\"status\":{\"completed\":\"done\"}}</subagent_notification>";
let carried_payload = writer.write_json_payload(
RawPayloadKind::AgentResult,
&json!({
"child_agent_path": "/root/child",
"message": notification,
"status": {"completed": "done"}
}),
)?;
writer.append_with_context(
trace_context_for_thread("019d0000-0000-7000-8000-000000000002", "turn-child-1"),
RawTraceEventPayload::AgentResultObserved {
edge_id: "edge:agent_result:thread-child:turn-child-1:thread-root".to_string(),
child_thread_id: "019d0000-0000-7000-8000-000000000002".to_string(),
child_codex_turn_id: "turn-child-1".to_string(),
parent_thread_id: "019d0000-0000-7000-8000-000000000001".to_string(),
message: notification.to_string(),
carried_payload: Some(carried_payload.clone()),
},
)?;
start_agent_turn(&writer, "turn-root-1")?;
let delivered = inter_agent_message(
"/root/child",
"/root",
notification,
/*trigger_turn*/ false,
);
append_inference_request(
&writer,
"019d0000-0000-7000-8000-000000000001",
"turn-root-1",
"inference-root-1",
vec![message("assistant", &delivered)],
)?;
let replayed = replay_bundle(temp.path())?;
let edge =
&replayed.interaction_edges["edge:agent_result:thread-child:turn-child-1:thread-root"];
assert_eq!(edge.kind, InteractionEdgeKind::AgentResult);
let TraceAnchor::ConversationItem {
item_id: source_item_id,
} = &edge.source
else {
panic!("expected child result conversation item source");
};
assert_eq!(
text_body(&replayed.conversation_items[source_item_id]),
"done"
);
let target_item_id = target_conversation_item_id(&edge.target);
assert_eq!(
replayed.conversation_items[target_item_id].thread_id,
"019d0000-0000-7000-8000-000000000001"
);
assert_eq!(edge.carried_item_ids, vec![target_item_id.clone()]);
assert_eq!(
edge.carried_raw_payload_ids,
vec![carried_payload.raw_payload_id]
);
Ok(())
}
#[test]
fn agent_result_edge_falls_back_to_child_thread_without_result_message() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_agent_writer(&temp)?;
// The child received its task but produced no assistant output. Failed
// child tasks can still notify the parent through AgentStatus, so the
// inbound task must not be mistaken for the child's result.
start_thread(
&writer,
"019d0000-0000-7000-8000-000000000002",
"/root/child",
)?;
start_turn_for_thread(
&writer,
"019d0000-0000-7000-8000-000000000002",
"turn-child-1",
)?;
append_inference_request(
&writer,
"019d0000-0000-7000-8000-000000000002",
"turn-child-1",
"inference-child-1",
vec![json!({
"type": "agent_message",
"author": "/root",
"recipient": "/root/child",
"content": [{"type": "input_text", "text": "do the task"}]
})],
)?;
let notification = r#"<subagent_notification>{"agent_path":"/root/child","status":{"failed":"boom"}}</subagent_notification>"#;
let carried_payload = writer.write_json_payload(
RawPayloadKind::AgentResult,
&json!({
"child_agent_path": "/root/child",
"message": notification,
"status": {"failed": "boom"}
}),
)?;
writer.append_with_context(
trace_context_for_thread("019d0000-0000-7000-8000-000000000002", "turn-child-1"),
RawTraceEventPayload::AgentResultObserved {
edge_id: "edge:agent_result:thread-child:turn-child-1:thread-root".to_string(),
child_thread_id: "019d0000-0000-7000-8000-000000000002".to_string(),
child_codex_turn_id: "turn-child-1".to_string(),
parent_thread_id: "019d0000-0000-7000-8000-000000000001".to_string(),
message: notification.to_string(),
carried_payload: Some(carried_payload.clone()),
},
)?;
// The parent does receive the failure notification as a model-visible
// mailbox item. The target should remain that precise parent-side
// ConversationItem even though the source falls back to the child thread.
start_agent_turn(&writer, "turn-root-1")?;
let delivered = inter_agent_message(
"/root/child",
"/root",
notification,
/*trigger_turn*/ false,
);
append_inference_request(
&writer,
"019d0000-0000-7000-8000-000000000001",
"turn-root-1",
"inference-root-1",
vec![message("assistant", &delivered)],
)?;
let replayed = replay_bundle(temp.path())?;
let edge =
&replayed.interaction_edges["edge:agent_result:thread-child:turn-child-1:thread-root"];
assert_eq!(edge.kind, InteractionEdgeKind::AgentResult);
assert_eq!(
edge.source,
TraceAnchor::Thread {
thread_id: "019d0000-0000-7000-8000-000000000002".to_string(),
}
);
let target_item_id = target_conversation_item_id(&edge.target);
assert_eq!(
replayed.conversation_items[target_item_id].thread_id,
"019d0000-0000-7000-8000-000000000001"
);
assert_eq!(edge.carried_item_ids, vec![target_item_id.clone()]);
assert_eq!(
edge.carried_raw_payload_ids,
vec![carried_payload.raw_payload_id]
);
Ok(())
}
struct SpawnAgentToolPayloads {
invocation: RawPayloadRef,
begin: RawPayloadRef,
end: RawPayloadRef,
result: RawPayloadRef,
}
fn append_spawn_agent_tool_lifecycle(
writer: &TraceWriter,
turn_id: &str,
) -> anyhow::Result<SpawnAgentToolPayloads> {
// Keep the parent-side tool lifecycle in one place so the spawn tests can
// focus on the child-side event that decides the edge target.
let invocation = writer.write_json_payload(
RawPayloadKind::ToolInvocation,
&json!({
"tool_name": "spawn_agent",
"payload": {
"type": "function",
"arguments": r#"{"task_name":"repo_file_counter","message":"count"}"#
}
}),
)?;
writer.append_with_context(
trace_context_for_agent(turn_id),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "call-spawn".to_string(),
model_visible_call_id: Some("call-spawn".to_string()),
code_mode_runtime_tool_id: None,
requester: RawToolCallRequester::Model,
kind: ToolCallKind::SpawnAgent,
summary: ToolCallSummary::Generic {
label: "spawn_agent".to_string(),
input_preview: None,
output_preview: None,
},
invocation_payload: Some(invocation.clone()),
},
)?;
let begin = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"call_id": "call-spawn",
"sender_thread_id": "019d0000-0000-7000-8000-000000000001",
"prompt": "count"
}),
)?;
writer.append_with_context(
trace_context_for_agent(turn_id),
RawTraceEventPayload::ToolCallRuntimeStarted {
kind: ToolCallKind::SpawnAgent,
tool_call_id: "call-spawn".to_string(),
runtime_payload: begin.clone(),
},
)?;
let end = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"call_id": "call-spawn",
"sender_thread_id": "019d0000-0000-7000-8000-000000000001",
"new_thread_id": "019d0000-0000-7000-8000-000000000002",
"prompt": "count",
"model": "gpt-test",
"reasoning_effort": "medium",
"status": "running"
}),
)?;
writer.append_with_context(
trace_context_for_agent(turn_id),
RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: "call-spawn".to_string(),
status: ExecutionStatus::Completed,
runtime_payload: end.clone(),
},
)?;
let result = writer.write_json_payload(
RawPayloadKind::ToolResult,
&json!({"task_name": "/root/repo_file_counter"}),
)?;
writer.append_with_context(
trace_context_for_agent(turn_id),
RawTraceEventPayload::ToolCallEnded {
tool_call_id: "call-spawn".to_string(),
status: ExecutionStatus::Completed,
result_payload: Some(result.clone()),
},
)?;
Ok(SpawnAgentToolPayloads {
invocation,
begin,
end,
result,
})
}
fn inter_agent_message(author: &str, recipient: &str, content: &str, trigger_turn: bool) -> String {
json!({
"author": author,
"recipient": recipient,
"other_recipients": [],
"content": content,
"trigger_turn": trigger_turn,
})
.to_string()
}
fn target_conversation_item_id(anchor: &TraceAnchor) -> &String {
let TraceAnchor::ConversationItem { item_id } = anchor else {
panic!("expected conversation item target");
};
item_id
}
fn text_body(item: &crate::model::ConversationItem) -> &str {
let [crate::model::ConversationPart::Text { text }] = item.body.parts.as_slice() else {
panic!("expected single text part");
};
text
}

View File

@@ -0,0 +1,131 @@
//! MCP identity regressions for callable aliases and backend names.
use std::sync::Arc;
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
use crate::ToolDispatchInvocation;
use crate::ToolDispatchPayload;
use crate::ToolDispatchRequester;
use crate::model::ToolCallKind;
use crate::payload::RawPayloadKind;
use crate::raw_event::RawTraceEventPayload;
use crate::reducer::test_support::ROOT_THREAD_ID;
use crate::reducer::test_support::append_completed_inference;
use crate::reducer::test_support::create_started_writer;
use crate::reducer::test_support::start_turn;
use crate::reducer::test_support::trace_context;
use crate::replay_bundle;
use crate::tool_dispatch::ToolDispatchTraceContext;
#[test]
fn mcp_calls_keep_callable_identity_and_classify_the_backend() -> anyhow::Result<()> {
// Both naming styles are aliases: neither the namespace nor the callable
// tool name determines the backend identity. All test data is invented.
for (namespace, tool_name, arguments) in [
("mcp__catalog", "lookup", "{}"),
("catalog_alias", "lookup", "{}"),
("catalog_alias", "exec_command", "{}"),
("catalog_alias", "send_message", "{}"),
("catalog_alias", "spawn_agent", "{}"),
("mcp__catalog", "write_stdin", "{}"),
("catalog_alias", "write_stdin", r#"{"session_id":123}"#),
] {
let temp = TempDir::new()?;
let writer = Arc::new(create_started_writer(&temp)?);
start_turn(&writer, "turn-1")?;
append_completed_inference(
&writer,
ROOT_THREAD_ID,
"turn-1",
"inference-1",
vec![],
vec![json!({
"type": "custom_tool_call", "name": "exec",
"call_id": "call-cell", "input": "await tools.call({})"
})],
)?;
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::CodeCellStarted {
runtime_cell_id: "cell-1".to_string(),
model_visible_call_id: "call-cell".to_string(),
source_js: "await tools.call({})".to_string(),
},
)?;
let _dispatch = ToolDispatchTraceContext::start(
Arc::clone(&writer),
ToolDispatchInvocation {
thread_id: ROOT_THREAD_ID.to_string(),
codex_turn_id: "turn-1".to_string(),
tool_call_id: "call-mcp".to_string(),
tool_name: tool_name.to_string(),
tool_namespace: Some(namespace.to_string()),
requester: ToolDispatchRequester::CodeCell {
runtime_cell_id: "cell-1".to_string(),
runtime_tool_call_id: "runtime-tool-1".to_string(),
},
payload: ToolDispatchPayload::Function {
arguments: arguments.to_string(),
},
},
);
let before = replay_bundle(temp.path())?;
// Namespaced write_stdin calls must neither require terminal arguments
// nor create terminal sessions when those arguments happen to be valid.
assert!(before.terminal_operations.is_empty());
assert!(before.terminal_sessions.is_empty());
let mut expected = before.tool_calls["call-mcp"].clone();
expected.kind = ToolCallKind::Mcp {
server: "inventory_service".to_string(),
tool: "find_item".to_string(),
};
let invocation = json!({
"server": "inventory_service", "tool": "find_item",
"arguments": serde_json::from_str::<serde_json::Value>(arguments)?
});
let begin = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"call_id": "call-mcp", "turn_id": "turn-1", "invocation": invocation
}),
)?;
writer.append(RawTraceEventPayload::ToolCallRuntimeStarted {
kind: expected.kind.clone(),
tool_call_id: "call-mcp".to_string(),
runtime_payload: begin.clone(),
})?;
expected.raw_runtime_payload_ids.push(begin.raw_payload_id);
// A live prefix must already have backend identity. Everything else,
// including the callable label, invocation reference and parent, stays.
assert_eq!(replay_bundle(temp.path())?.tool_calls["call-mcp"], expected);
// The producer emits the runtime begin before assigning its MCP
// correlation ID, even when the callable name matches a built-in.
writer.append(RawTraceEventPayload::McpToolCallCorrelationAssigned {
tool_call_id: "call-mcp".to_string(),
mcp_call_id: "mcp-correlation-1".to_string(),
})?;
expected.mcp_call_id = Some("mcp-correlation-1".to_string());
let end = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"call_id": "call-mcp", "turn_id": "turn-1", "invocation": invocation,
"duration": {"secs": 0, "nanos": 1}, "result": {"Ok": {"content": []}}
}),
)?;
writer.append(RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: "call-mcp".to_string(),
status: crate::ExecutionStatus::Completed,
runtime_payload: end.clone(),
})?;
expected.raw_runtime_payload_ids.push(end.raw_payload_id);
// MCP completion must not overwrite the outer dispatch lifecycle.
assert_eq!(replay_bundle(temp.path())?.tool_calls["call-mcp"], expected);
}
Ok(())
}

View File

@@ -0,0 +1,660 @@
//! Terminal reduction for exec-like tool calls.
//!
//! The raw trace records terminal activity as normal tool lifecycle events.
//! Protocol-backed exec events carry `ExecCommand*` payloads with the richest
//! runtime details. Direct tools without protocol observations, such as
//! `write_stdin`, can still form a terminal row from the canonical dispatch
//! invocation/result payloads when those payloads carry the session join key.
//! Runtime process handles are recyclable and thread-local. Each exec creates a
//! distinct reduced session; stdin uses the runtime's resolved exec when recorded,
//! falling back to the latest session for its handle in older traces.
use anyhow::Context;
use anyhow::Result;
use anyhow::bail;
use serde::Deserialize;
use serde_json::Value as JsonValue;
use super::push_unique;
use crate::model::ExecutionStatus;
use crate::model::ExecutionWindow;
use crate::model::TerminalModelObservation;
use crate::model::TerminalObservationSource;
use crate::model::TerminalOperation;
use crate::model::TerminalOperationId;
use crate::model::TerminalOperationKind;
use crate::model::TerminalRequest;
use crate::model::TerminalResult;
use crate::model::TerminalSession;
use crate::model::ToolCallKind;
use crate::payload::RawPayloadRef;
use crate::raw_event::RawEventSeq;
use crate::reducer::TraceReducer;
impl TraceReducer {
/// Starts a terminal operation from a canonical dispatch invocation payload.
///
/// This is currently needed for direct tools such as write-stdin that do not
/// emit a richer protocol runtime-begin event with the terminal join key.
pub(in crate::reducer) fn start_terminal_operation_from_invocation(
&mut self,
seq: RawEventSeq,
wall_time_unix_ms: i64,
thread_id: &str,
tool_call_id: &str,
kind: &ToolCallKind,
invocation_payload: Option<&RawPayloadRef>,
) -> Result<Option<TerminalOperationId>> {
if !matches!(kind, ToolCallKind::WriteStdin) {
return Ok(None);
}
let operation_kind = TerminalOperationKind::WriteStdin;
let Some(invocation_payload) = invocation_payload else {
// Payload writes are best-effort in the live recorder. If the
// canonical invocation is missing, keep the ToolCall but avoid
// fabricating a lossy terminal row.
return Ok(None);
};
let payload = self.read_payload_json(invocation_payload)?;
let Some(request) = parse_dispatch_terminal_request(payload).with_context(|| {
format!(
"parse terminal invocation payload {} as dispatch payload",
invocation_payload.raw_payload_id
)
})?
else {
return Ok(None);
};
self.insert_terminal_operation(TerminalOperationStart {
seq,
wall_time_unix_ms,
thread_id,
tool_call_id,
operation_kind,
raw_payload: invocation_payload,
request,
})
}
/// Starts a terminal operation from a protocol runtime-begin payload.
pub(in crate::reducer) fn start_terminal_operation_from_runtime(
&mut self,
seq: RawEventSeq,
wall_time_unix_ms: i64,
thread_id: &str,
tool_call_id: &str,
kind: &ToolCallKind,
runtime_payload: &RawPayloadRef,
) -> Result<Option<TerminalOperationId>> {
let Some(operation_kind) = terminal_operation_kind(kind) else {
return Ok(None);
};
let payload = self.read_payload_json(runtime_payload)?;
let payload: ExecCommandBeginPayload =
serde_json::from_value(payload).with_context(|| {
format!(
"parse terminal runtime start payload {}",
runtime_payload.raw_payload_id
)
})?;
let request = parse_protocol_terminal_request(payload, &operation_kind);
self.insert_terminal_operation(TerminalOperationStart {
seq,
wall_time_unix_ms,
thread_id,
tool_call_id,
operation_kind,
raw_payload: runtime_payload,
request,
})
}
fn insert_terminal_operation(
&mut self,
start: TerminalOperationStart<'_>,
) -> Result<Option<TerminalOperationId>> {
let operation_id = self.next_terminal_operation_id();
let ParsedTerminalRequest {
process_id,
request,
} = start.request;
self.rollout.terminal_operations.insert(
operation_id.clone(),
TerminalOperation {
operation_id: operation_id.clone(),
terminal_id: None,
tool_call_id: start.tool_call_id.to_string(),
kind: start.operation_kind,
execution: ExecutionWindow {
started_at_unix_ms: start.wall_time_unix_ms,
started_seq: start.seq,
ended_at_unix_ms: None,
ended_seq: None,
status: ExecutionStatus::Running,
},
request,
result: None,
model_observations: Vec::new(),
raw_payload_ids: vec![start.raw_payload.raw_payload_id.clone()],
},
);
if let Some(process_id) = process_id {
self.attach_terminal_session(start.thread_id, &process_id, &operation_id)?;
}
Ok(Some(operation_id))
}
/// Completes the terminal operation associated with a tool call, if one exists.
///
/// Non-terminal tools flow through the same generic tool lifecycle, so callers
/// may invoke this unconditionally and receive Ok for unrelated tool kinds.
pub(in crate::reducer) fn end_terminal_operation(
&mut self,
seq: RawEventSeq,
wall_time_unix_ms: i64,
thread_id: &str,
operation_id: &str,
status: ExecutionStatus,
response_payload: Option<&RawPayloadRef>,
) -> Result<()> {
let Some(operation_kind) = self
.rollout
.terminal_operations
.get(operation_id)
.map(|operation| operation.kind.clone())
else {
bail!("terminal end referenced unknown operation {operation_id}");
};
let response = response_payload
.map(|payload| {
let value = self.read_payload_json(payload)?;
let response = parse_terminal_response_payload(
value,
&operation_kind,
&payload.raw_payload_id,
)?;
Ok::<_, anyhow::Error>((payload.raw_payload_id.clone(), response))
})
.transpose()?;
let process_id = {
let Some(operation) = self.rollout.terminal_operations.get_mut(operation_id) else {
bail!("terminal end referenced unknown operation {operation_id}");
};
operation.execution.ended_at_unix_ms = Some(wall_time_unix_ms);
operation.execution.ended_seq = Some(seq);
operation.execution.status = status;
if let Some((raw_payload_id, response)) = response {
push_unique(&mut operation.raw_payload_ids, &raw_payload_id);
operation.result = Some(response.result);
response.process_id
} else {
None
}
};
if let Some(process_id) = process_id {
self.attach_terminal_session(thread_id, &process_id, operation_id)?;
}
Ok(())
}
fn attach_terminal_session(
&mut self,
thread_id: &str,
process_id: &str,
operation_id: &str,
) -> Result<()> {
let Some(operation) = self.rollout.terminal_operations.get_mut(operation_id) else {
bail!("terminal session referenced unknown operation {operation_id}");
};
if let Some(terminal_id) = &operation.terminal_id {
let existing = &self.process_ids_by_terminal[terminal_id];
if existing != process_id {
bail!(
"terminal operation {operation_id} changed process id from {existing} to {process_id}"
);
}
return Ok(());
}
let key = (thread_id.to_string(), process_id.to_string());
let existing = match operation.kind {
TerminalOperationKind::ExecCommand => None,
TerminalOperationKind::WriteStdin => self.terminal_ids_by_process.get(&key).cloned(),
};
let terminal_id = existing.unwrap_or_else(|| format!("terminal_session:{operation_id}"));
let session = self
.rollout
.terminal_sessions
.entry(terminal_id.clone())
.or_insert_with(|| TerminalSession {
terminal_id: terminal_id.clone(),
thread_id: thread_id.to_string(),
created_by_operation_id: operation_id.to_string(),
operation_ids: Vec::new(),
execution: ExecutionWindow {
started_at_unix_ms: operation.execution.started_at_unix_ms,
started_seq: operation.execution.started_seq,
// Raw events do not report session release: buffered output
// can still be collected after the process exits.
ended_at_unix_ms: None,
ended_seq: None,
status: ExecutionStatus::Running,
},
});
push_unique(&mut session.operation_ids, operation_id);
operation.terminal_id = Some(terminal_id.clone());
self.process_ids_by_terminal
.insert(terminal_id.clone(), process_id.to_string());
self.terminal_ids_by_process.insert(key, terminal_id);
Ok(())
}
/// Replaces the provisional handle-based join with the runtime's actual target.
pub(in crate::reducer) fn resolve_stdin_target(
&mut self,
tool_call_id: &str,
exec_tool_call_id: &str,
) -> Result<()> {
let stdin = self
.rollout
.tool_calls
.get(tool_call_id)
.with_context(|| format!("stdin target referenced unknown call {tool_call_id}"))?;
let exec = self
.rollout
.tool_calls
.get(exec_tool_call_id)
.with_context(|| format!("stdin target referenced unknown exec {exec_tool_call_id}"))?;
let (Some(operation_id), Some(exec_operation_id)) =
(&stdin.terminal_operation_id, &exec.terminal_operation_id)
else {
// A failed payload write can leave either call without a terminal projection.
return Ok(());
};
let Some(terminal_id) = self.rollout.terminal_operations[exec_operation_id]
.terminal_id
.clone()
else {
return Ok(());
};
let operation = self
.rollout
.terminal_operations
.get_mut(operation_id)
.with_context(|| format!("stdin target referenced unknown operation {operation_id}"))?;
if operation.terminal_id.as_ref() == Some(&terminal_id) {
return Ok(());
}
// Move this operation without rewinding the handle lookup: a newer exec
// may already own that handle by the time resolution is recorded.
if let Some(previous) = operation.terminal_id.replace(terminal_id.clone()) {
let session = self
.rollout
.terminal_sessions
.get_mut(&previous)
.with_context(|| format!("stdin target referenced unknown session {previous}"))?;
session.operation_ids.retain(|id| id != operation_id);
if session.operation_ids.is_empty() {
self.rollout.terminal_sessions.remove(&previous);
self.process_ids_by_terminal.remove(&previous);
}
}
self.rollout
.terminal_sessions
.get_mut(&terminal_id)
.with_context(|| format!("stdin target referenced unknown session {terminal_id}"))?
.operation_ids
.push(operation_id.clone());
Ok(())
}
/// Mirrors model-visible tool items onto the terminal observation view.
///
/// Runtime terminal rows are useful on their own, but the model-visible call
/// and output item ids let viewers jump between transcript and terminal timelines.
pub(in crate::reducer) fn sync_terminal_model_observation(
&mut self,
tool_call_id: &str,
) -> Result<()> {
let Some(tool_call) = self.rollout.tool_calls.get(tool_call_id) else {
bail!("tool call {tool_call_id} disappeared during terminal observation linking");
};
let Some(operation_id) = tool_call.terminal_operation_id.clone() else {
return Ok(());
};
let call_item_ids = tool_call.model_visible_call_item_ids.clone();
let output_item_ids = tool_call.model_visible_output_item_ids.clone();
if call_item_ids.is_empty() && output_item_ids.is_empty() {
return Ok(());
}
let Some(operation) = self.rollout.terminal_operations.get_mut(&operation_id) else {
bail!("terminal operation {operation_id} disappeared during observation linking");
};
// A terminal result and a model-visible tool output are intentionally
// separate: the former is what the runtime saw, the latter is what later
// inference payloads prove was shown back to the model.
if let Some(observation) = operation
.model_observations
.iter_mut()
.find(|observation| observation.source == TerminalObservationSource::DirectToolCall)
{
observation.call_item_ids = call_item_ids;
observation.output_item_ids = output_item_ids;
} else {
operation.model_observations.push(TerminalModelObservation {
call_item_ids,
output_item_ids,
source: TerminalObservationSource::DirectToolCall,
});
}
Ok(())
}
fn next_terminal_operation_id(&mut self) -> TerminalOperationId {
let ordinal = self.next_terminal_operation_ordinal;
self.next_terminal_operation_ordinal += 1;
format!("terminal_operation:{ordinal}")
}
}
fn terminal_operation_kind(kind: &ToolCallKind) -> Option<TerminalOperationKind> {
match kind {
ToolCallKind::ExecCommand => Some(TerminalOperationKind::ExecCommand),
ToolCallKind::WriteStdin => Some(TerminalOperationKind::WriteStdin),
ToolCallKind::ApplyPatch
| ToolCallKind::Mcp { .. }
| ToolCallKind::Web
| ToolCallKind::ImageGeneration
| ToolCallKind::SpawnAgent
| ToolCallKind::AssignAgentTask
| ToolCallKind::SendMessage
| ToolCallKind::WaitAgent
| ToolCallKind::CloseAgent
| ToolCallKind::Other { .. } => None,
}
}
struct TerminalOperationStart<'a> {
seq: RawEventSeq,
wall_time_unix_ms: i64,
thread_id: &'a str,
tool_call_id: &'a str,
operation_kind: TerminalOperationKind,
raw_payload: &'a RawPayloadRef,
request: ParsedTerminalRequest,
}
struct ParsedTerminalRequest {
process_id: Option<String>,
request: TerminalRequest,
}
struct ParsedTerminalResponse {
process_id: Option<String>,
result: TerminalResult,
}
fn parse_protocol_terminal_request(
payload: ExecCommandBeginPayload,
operation_kind: &TerminalOperationKind,
) -> ParsedTerminalRequest {
// Startup/poll paths usually include a process id at begin time, but plain
// exec starts may only learn it in the matching end event.
let process_id = payload.process_id.clone();
let request = match operation_kind {
TerminalOperationKind::ExecCommand => TerminalRequest::ExecCommand {
display_command: payload.command.join(" "),
command: payload.command,
cwd: payload.cwd,
yield_time_ms: None,
max_output_tokens: None,
},
TerminalOperationKind::WriteStdin => TerminalRequest::WriteStdin {
stdin: payload.interaction_input.unwrap_or_default(),
yield_time_ms: None,
max_output_tokens: None,
},
};
ParsedTerminalRequest {
process_id,
request,
}
}
fn parse_dispatch_terminal_request(value: JsonValue) -> Result<Option<ParsedTerminalRequest>> {
let payload: DispatchedToolTraceRequestPayload = serde_json::from_value(value)?;
// Recorded kinds are name-based. Only the built-in write_stdin owns terminal
// sessions; core records its default namespace as None. Namespaced aliases
// must wait for runtime classification, even if their arguments look native.
if payload.tool_namespace.is_some() {
return Ok(None);
}
if payload.tool_name != "write_stdin" {
bail!(
"dispatch terminal request is for {}, not write_stdin",
payload.tool_name
);
}
if payload.payload.kind != "function" {
bail!(
"write_stdin dispatch payload used unsupported {} payload",
payload.payload.kind
);
}
let arguments = payload
.payload
.arguments
.context("write_stdin dispatch payload omitted function arguments")?;
// Invalid model arguments are a tool failure, not a corrupt trace. Keep the
// generic call and its error without inventing a terminal operation.
let Ok(args) = serde_json::from_str::<DispatchedWriteStdinArgs>(&arguments) else {
return Ok(None);
};
let Some(process_id) = process_id_from_json(&args.session_id) else {
return Ok(None);
};
Ok(Some(ParsedTerminalRequest {
process_id: Some(process_id),
request: TerminalRequest::WriteStdin {
stdin: args.chars,
yield_time_ms: args.yield_time_ms,
max_output_tokens: args.max_output_tokens,
},
}))
}
fn parse_terminal_response_payload(
value: JsonValue,
operation_kind: &TerminalOperationKind,
raw_payload_id: &str,
) -> Result<ParsedTerminalResponse> {
match operation_kind {
TerminalOperationKind::ExecCommand => {
let payload = serde_json::from_value::<ExecCommandEndPayload>(value)
.with_context(|| format!("parse exec terminal response {raw_payload_id}"))?;
Ok(parse_protocol_terminal_response(payload))
}
TerminalOperationKind::WriteStdin => {
match serde_json::from_value::<ExecCommandEndPayload>(value.clone()) {
Ok(payload) => Ok(parse_protocol_terminal_response(payload)),
Err(protocol_err) => parse_dispatch_terminal_response(value).with_context(|| {
format!(
"parse write_stdin terminal response {raw_payload_id} as protocol payload \
({protocol_err}) or dispatch payload"
)
}),
}
}
}
}
fn parse_protocol_terminal_response(payload: ExecCommandEndPayload) -> ParsedTerminalResponse {
ParsedTerminalResponse {
process_id: payload.process_id,
result: TerminalResult {
exit_code: Some(payload.exit_code),
stdout: payload.aggregated_output,
stderr: String::new(),
formatted_output: None,
original_token_count: None,
chunk_id: None,
},
}
}
fn parse_dispatch_terminal_response(value: JsonValue) -> Result<ParsedTerminalResponse> {
let payload: DispatchedToolTraceResponsePayload = serde_json::from_value(value)?;
let result = match payload {
DispatchedToolTraceResponsePayload::DirectResponse { response_item } => {
let output = response_item
.get("output")
.and_then(json_text_content)
.unwrap_or_else(|| response_item.to_string());
TerminalResult {
exit_code: None,
stdout: output.clone(),
stderr: String::new(),
formatted_output: Some(output),
original_token_count: None,
chunk_id: None,
}
}
DispatchedToolTraceResponsePayload::CodeModeResponse { value } => {
// Code-mode returns the JavaScript-facing tool value, not the text
// shown to the model. For write_stdin that value is the structured
// unified-exec result, so keep ToolCall.raw_result_payload_id as the
// raw boundary while projecting terminal-specific fields here.
parse_code_mode_exec_result(value)
}
DispatchedToolTraceResponsePayload::Error { error } => TerminalResult {
exit_code: None,
stdout: String::new(),
stderr: error.clone(),
formatted_output: Some(error),
original_token_count: None,
chunk_id: None,
},
};
Ok(ParsedTerminalResponse {
process_id: None,
result,
})
}
fn parse_code_mode_exec_result(value: JsonValue) -> TerminalResult {
match serde_json::from_value::<CodeModeExecResult>(value.clone()) {
Ok(result) => TerminalResult {
exit_code: result.exit_code,
stdout: result.output.clone(),
stderr: String::new(),
formatted_output: Some(result.output),
original_token_count: result.original_token_count,
chunk_id: result.chunk_id,
},
Err(_) => {
let output = json_text_content(&value).unwrap_or_else(|| value.to_string());
TerminalResult {
exit_code: None,
stdout: output.clone(),
stderr: String::new(),
formatted_output: Some(output),
original_token_count: None,
chunk_id: None,
}
}
}
}
fn json_text_content(value: &JsonValue) -> Option<String> {
match value {
JsonValue::String(text) => Some(text.clone()),
JsonValue::Array(items) => {
let text = items
.iter()
.filter_map(|item| item.get("text").and_then(JsonValue::as_str))
.collect::<Vec<_>>()
.join("\n");
(!text.is_empty()).then_some(text)
}
JsonValue::Null => None,
other => Some(other.to_string()),
}
}
fn process_id_from_json(value: &JsonValue) -> Option<String> {
match value {
JsonValue::String(value) if !value.is_empty() => Some(value.clone()),
JsonValue::Number(value) => Some(value.to_string()),
_ => None,
}
}
#[derive(Deserialize)]
struct ExecCommandBeginPayload {
process_id: Option<String>,
command: Vec<String>,
cwd: String,
interaction_input: Option<String>,
}
#[derive(Deserialize)]
struct ExecCommandEndPayload {
process_id: Option<String>,
#[serde(default)]
aggregated_output: String,
exit_code: i32,
}
#[derive(Deserialize)]
struct DispatchedToolTraceRequestPayload {
tool_name: String,
tool_namespace: Option<String>,
payload: DispatchedToolPayload,
}
#[derive(Deserialize)]
struct DispatchedToolPayload {
#[serde(rename = "type")]
kind: String,
arguments: Option<String>,
}
#[derive(Deserialize)]
struct DispatchedWriteStdinArgs {
session_id: JsonValue,
#[serde(default)]
chars: String,
yield_time_ms: Option<u64>,
max_output_tokens: Option<usize>,
}
#[derive(Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
enum DispatchedToolTraceResponsePayload {
DirectResponse { response_item: JsonValue },
CodeModeResponse { value: JsonValue },
Error { error: String },
}
#[derive(Deserialize)]
struct CodeModeExecResult {
chunk_id: Option<String>,
exit_code: Option<i32>,
original_token_count: Option<usize>,
output: String,
}
#[cfg(test)]
#[path = "terminal_tests.rs"]
mod tests;

View File

@@ -0,0 +1,708 @@
use std::sync::Arc;
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
use crate::ToolDispatchInvocation;
use crate::ToolDispatchPayload;
use crate::ToolDispatchRequester;
use crate::model::ExecutionStatus;
use crate::model::ExecutionWindow;
use crate::model::RolloutStatus;
use crate::model::TerminalModelObservation;
use crate::model::TerminalObservationSource;
use crate::model::TerminalOperation;
use crate::model::TerminalOperationKind;
use crate::model::TerminalRequest;
use crate::model::TerminalResult;
use crate::model::TerminalSession;
use crate::model::ToolCallKind;
use crate::model::ToolCallSummary;
use crate::payload::RawPayloadKind;
use crate::raw_event::RawTraceEventPayload;
use crate::reducer::test_support::ROOT_THREAD_ID;
use crate::reducer::test_support::create_started_writer;
use crate::reducer::test_support::generic_summary;
use crate::reducer::test_support::message;
use crate::reducer::test_support::start_thread;
use crate::reducer::test_support::start_turn;
use crate::reducer::test_support::start_turn_for_thread;
use crate::reducer::test_support::trace_context;
use crate::reducer::test_support::trace_context_for_thread;
use crate::replay_bundle;
use crate::tool_dispatch::ToolDispatchTraceContext;
use crate::writer::TraceWriter;
#[test]
fn exec_tool_reduces_to_terminal_operation_and_session() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_writer(&temp)?;
start_turn(&writer, "turn-1")?;
append_inference_with_tool_call(&writer)?;
let invocation_payload = writer.write_json_payload(
RawPayloadKind::ToolInvocation,
&json!({
"tool_name": "exec_command",
"tool_namespace": null,
"payload": {
"type": "function",
"arguments": "{\"cmd\":\"cargo test\"}"
}
}),
)?;
let invocation_payload_id = invocation_payload.raw_payload_id.clone();
let _tool_start = writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "tool-1".to_string(),
model_visible_call_id: Some("call-1".to_string()),
code_mode_runtime_tool_id: None,
requester: crate::raw_event::RawToolCallRequester::Model,
kind: ToolCallKind::ExecCommand,
summary: generic_summary("exec_command"),
invocation_payload: Some(invocation_payload),
},
)?;
let runtime_start_payload = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"call_id": "tool-1",
"turn_id": "turn-1",
"command": ["cargo", "test"],
"cwd": "/repo"
}),
)?;
let runtime_start_payload_id = runtime_start_payload.raw_payload_id.clone();
let runtime_start = writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallRuntimeStarted {
kind: ToolCallKind::ExecCommand,
tool_call_id: "tool-1".to_string(),
runtime_payload: runtime_start_payload,
},
)?;
let runtime_end_payload = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"call_id": "tool-1",
"process_id": "pty-1",
"turn_id": "turn-1",
"command": ["cargo", "test"],
"cwd": "/repo",
"aggregated_output": "ok\n",
"exit_code": 0,
"status": "completed"
}),
)?;
let runtime_end_payload_id = runtime_end_payload.raw_payload_id.clone();
let runtime_end = writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: "tool-1".to_string(),
status: ExecutionStatus::Completed,
runtime_payload: runtime_end_payload,
},
)?;
let result_payload = writer.write_json_payload(
RawPayloadKind::ToolResult,
&json!({
"type": "direct_response",
"response_item": {
"type": "function_call_output",
"call_id": "call-1",
"output": "ok\n"
}
}),
)?;
let result_payload_id = result_payload.raw_payload_id.clone();
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallEnded {
tool_call_id: "tool-1".to_string(),
status: ExecutionStatus::Completed,
result_payload: Some(result_payload),
},
)?;
start_turn(&writer, "turn-2")?;
append_followup_with_tool_output(&writer)?;
let rollout = replay_bundle(temp.path())?;
let operation_id = "terminal_operation:1".to_string();
let output_item_id = rollout.inference_calls["inference-2"]
.request_item_ids
.last()
.expect("tool output item")
.clone();
assert_eq!(
rollout.tool_calls["tool-1"].terminal_operation_id,
Some(operation_id.clone()),
);
assert_eq!(
rollout.tool_calls["tool-1"].raw_invocation_payload_id,
Some(invocation_payload_id),
);
assert_eq!(
rollout.tool_calls["tool-1"].raw_result_payload_id,
Some(result_payload_id),
);
assert_eq!(
rollout.tool_calls["tool-1"].raw_runtime_payload_ids,
vec![
runtime_start_payload_id.clone(),
runtime_end_payload_id.clone()
],
);
assert_eq!(
rollout.tool_calls["tool-1"].summary,
ToolCallSummary::Terminal {
operation_id: operation_id.clone(),
},
);
assert_eq!(
rollout.terminal_operations[&operation_id],
TerminalOperation {
operation_id: operation_id.clone(),
terminal_id: Some("terminal_session:terminal_operation:1".to_string()),
tool_call_id: "tool-1".to_string(),
kind: TerminalOperationKind::ExecCommand,
execution: ExecutionWindow {
started_at_unix_ms: runtime_start.wall_time_unix_ms,
started_seq: runtime_start.seq,
ended_at_unix_ms: Some(runtime_end.wall_time_unix_ms),
ended_seq: Some(runtime_end.seq),
status: ExecutionStatus::Completed,
},
request: TerminalRequest::ExecCommand {
command: vec!["cargo".to_string(), "test".to_string()],
display_command: "cargo test".to_string(),
cwd: "/repo".to_string(),
yield_time_ms: None,
max_output_tokens: None,
},
result: Some(TerminalResult {
exit_code: Some(0),
stdout: "ok\n".to_string(),
stderr: String::new(),
formatted_output: None,
original_token_count: None,
chunk_id: None,
}),
model_observations: vec![TerminalModelObservation {
call_item_ids: rollout.inference_calls["inference-1"]
.response_item_ids
.clone(),
output_item_ids: vec![output_item_id],
source: TerminalObservationSource::DirectToolCall,
}],
raw_payload_ids: vec![runtime_start_payload_id, runtime_end_payload_id],
},
);
assert_eq!(
rollout.terminal_sessions["terminal_session:terminal_operation:1"],
TerminalSession {
terminal_id: "terminal_session:terminal_operation:1".to_string(),
thread_id: "thread-root".to_string(),
created_by_operation_id: operation_id.clone(),
operation_ids: vec![operation_id],
execution: ExecutionWindow {
started_at_unix_ms: runtime_start.wall_time_unix_ms,
started_seq: runtime_start.seq,
ended_at_unix_ms: None,
ended_seq: None,
status: ExecutionStatus::Running,
},
},
);
Ok(())
}
#[test]
fn reused_process_ids_keep_sessions_and_stdin_joins_distinct() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_writer(&temp)?;
start_turn(&writer, "turn-1")?;
start_thread(&writer, "child", "/root/child")?;
start_turn_for_thread(&writer, "child", "child-turn")?;
let mut reused_stdin = None;
// Real rollouts reuse process IDs both across threads and after an exec
// finishes. Polls must stay with the corresponding exec, not the last
// occurrence of the process number anywhere in the rollout.
for (index, (thread, turn, kind)) in [
("thread-root", "turn-1", ToolCallKind::ExecCommand),
("child", "child-turn", ToolCallKind::ExecCommand),
("thread-root", "turn-1", ToolCallKind::WriteStdin),
("child", "child-turn", ToolCallKind::WriteStdin),
("thread-root", "turn-1", ToolCallKind::ExecCommand),
("thread-root", "turn-1", ToolCallKind::WriteStdin),
("child", "resumed-turn", ToolCallKind::WriteStdin),
]
.into_iter()
.enumerate()
{
if turn == "resumed-turn" {
writer.append(RawTraceEventPayload::ThreadEnded {
thread_id: thread.to_string(),
status: RolloutStatus::Completed,
})?;
writer.append(RawTraceEventPayload::ThreadResumed {
thread_id: thread.to_string(),
})?;
start_turn_for_thread(&writer, thread, turn)?;
}
if index == 4 {
let response = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({"process_id": "123", "exit_code": 0}),
)?;
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: "tool-0".to_string(),
status: ExecutionStatus::Completed,
runtime_payload: response,
},
)?;
}
let tool_call_id = format!("tool-{index}");
writer.append_with_context(
trace_context_for_thread(thread, turn),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: tool_call_id.clone(),
model_visible_call_id: None,
code_mode_runtime_tool_id: None,
requester: crate::raw_event::RawToolCallRequester::Model,
kind: kind.clone(),
summary: generic_summary("terminal"),
invocation_payload: None,
},
)?;
let request = writer.write_json_payload(
RawPayloadKind::ToolRuntimeEvent,
&json!({
"process_id": "123",
"command": ["bash"],
"cwd": "/repo",
"interaction_input": (index == 5).then_some("echo hi\n"),
}),
)?;
let request_id = request.raw_payload_id.clone();
let runtime_start = writer.append_with_context(
trace_context_for_thread(thread, turn),
RawTraceEventPayload::ToolCallRuntimeStarted {
kind,
tool_call_id,
runtime_payload: request,
},
)?;
if index == 5 {
reused_stdin = Some((runtime_start, request_id));
}
}
let rollout = replay_bundle(temp.path())?;
let groups = rollout
.terminal_sessions
.values()
.map(|session| {
let calls = session
.operation_ids
.iter()
.map(|id| {
let operation = &rollout.terminal_operations[id];
assert_eq!(operation.terminal_id.as_ref(), Some(&session.terminal_id));
operation.tool_call_id.as_str()
})
.collect::<Vec<_>>();
(session.thread_id.as_str(), calls)
})
.collect::<Vec<_>>();
assert_eq!(
groups,
vec![
("thread-root", vec!["tool-0", "tool-2"]),
("child", vec!["tool-1", "tool-3"]),
("thread-root", vec!["tool-4", "tool-5"]),
("child", vec!["tool-6"]),
],
);
let (runtime_start, request_id) = reused_stdin.unwrap();
assert_eq!(
rollout.terminal_operations["terminal_operation:6"],
TerminalOperation {
operation_id: "terminal_operation:6".to_string(),
terminal_id: Some("terminal_session:terminal_operation:5".to_string()),
tool_call_id: "tool-5".to_string(),
kind: TerminalOperationKind::WriteStdin,
execution: ExecutionWindow {
started_at_unix_ms: runtime_start.wall_time_unix_ms,
started_seq: runtime_start.seq,
ended_at_unix_ms: None,
ended_seq: None,
status: ExecutionStatus::Running,
},
request: TerminalRequest::WriteStdin {
stdin: "echo hi\n".to_string(),
yield_time_ms: None,
max_output_tokens: None,
},
result: None,
model_observations: Vec::new(),
raw_payload_ids: vec![request_id],
},
);
// Stdin started while tool-0 owned the handle, but dispatch was delayed
// until tool-4 replaced it. Only its session membership should change.
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::StdinTargetResolved {
tool_call_id: "tool-2".to_string(),
exec_tool_call_id: "tool-4".to_string(),
},
)?;
let mut expected = rollout;
let previous = "terminal_session:terminal_operation:1";
let resolved = "terminal_session:terminal_operation:5";
expected
.terminal_sessions
.get_mut(previous)
.unwrap()
.operation_ids = vec!["terminal_operation:1".to_string()];
expected
.terminal_sessions
.get_mut(resolved)
.unwrap()
.operation_ids
.push("terminal_operation:3".to_string());
expected
.terminal_operations
.get_mut("terminal_operation:3")
.unwrap()
.terminal_id = Some(resolved.to_string());
assert_eq!(replay_bundle(temp.path())?, expected);
Ok(())
}
#[test]
fn dispatch_write_stdin_payload_reduces_to_terminal_operation() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_writer(&temp)?;
start_turn(&writer, "turn-1")?;
let request_payload = writer.write_json_payload(
RawPayloadKind::ToolInvocation,
&json!({
"tool_name": "write_stdin",
"tool_namespace": null,
"payload": {
"type": "function",
"arguments": json!({
"session_id": 123,
"chars": "echo hi\n",
"yield_time_ms": 250,
"max_output_tokens": 2000
}).to_string()
}
}),
)?;
let request_payload_id = request_payload.raw_payload_id.clone();
let tool_start = writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "tool-stdin".to_string(),
model_visible_call_id: Some("call-stdin".to_string()),
code_mode_runtime_tool_id: None,
requester: crate::raw_event::RawToolCallRequester::Model,
kind: ToolCallKind::WriteStdin,
summary: generic_summary("write_stdin"),
invocation_payload: Some(request_payload),
},
)?;
let response_payload = writer.write_json_payload(
RawPayloadKind::ToolResult,
&json!({
"type": "direct_response",
"response_item": {
"type": "function_call_output",
"call_id": "call-stdin",
"output": "hi\n"
}
}),
)?;
let response_payload_id = response_payload.raw_payload_id.clone();
let tool_end = writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallEnded {
tool_call_id: "tool-stdin".to_string(),
status: ExecutionStatus::Completed,
result_payload: Some(response_payload),
},
)?;
let rollout = replay_bundle(temp.path())?;
let operation_id = "terminal_operation:1".to_string();
assert_eq!(
rollout.tool_calls["tool-stdin"].terminal_operation_id,
Some(operation_id.clone()),
);
assert_eq!(
rollout.tool_calls["tool-stdin"].summary,
ToolCallSummary::Terminal {
operation_id: operation_id.clone(),
},
);
assert_eq!(
rollout.terminal_operations[&operation_id],
TerminalOperation {
operation_id: operation_id.clone(),
terminal_id: Some("terminal_session:terminal_operation:1".to_string()),
tool_call_id: "tool-stdin".to_string(),
kind: TerminalOperationKind::WriteStdin,
execution: ExecutionWindow {
started_at_unix_ms: tool_start.wall_time_unix_ms,
started_seq: tool_start.seq,
ended_at_unix_ms: Some(tool_end.wall_time_unix_ms),
ended_seq: Some(tool_end.seq),
status: ExecutionStatus::Completed,
},
request: TerminalRequest::WriteStdin {
stdin: "echo hi\n".to_string(),
yield_time_ms: Some(250),
max_output_tokens: Some(2000),
},
result: Some(TerminalResult {
exit_code: None,
stdout: "hi\n".to_string(),
stderr: String::new(),
formatted_output: Some("hi\n".to_string()),
original_token_count: None,
chunk_id: None,
}),
model_observations: Vec::new(),
raw_payload_ids: vec![request_payload_id, response_payload_id],
},
);
assert_eq!(
rollout.terminal_sessions["terminal_session:terminal_operation:1"],
TerminalSession {
terminal_id: "terminal_session:terminal_operation:1".to_string(),
thread_id: "thread-root".to_string(),
created_by_operation_id: operation_id.clone(),
operation_ids: vec![operation_id],
execution: ExecutionWindow {
started_at_unix_ms: tool_start.wall_time_unix_ms,
started_seq: tool_start.seq,
ended_at_unix_ms: None,
ended_seq: None,
status: ExecutionStatus::Running,
},
},
);
Ok(())
}
#[test]
fn invalid_write_stdin_arguments_remain_failed_tool_calls() -> anyhow::Result<()> {
for arguments in [r#"{"session_id": "#, "{}", r#"{"session_id": null}"#] {
let temp = TempDir::new()?;
let writer = Arc::new(create_started_writer(&temp)?);
start_turn(&writer, "turn-1")?;
let dispatch = ToolDispatchTraceContext::start(
Arc::clone(&writer),
ToolDispatchInvocation {
thread_id: ROOT_THREAD_ID.to_string(),
codex_turn_id: "turn-1".to_string(),
tool_call_id: "call-stdin".to_string(),
tool_name: "write_stdin".to_string(),
tool_namespace: None,
requester: ToolDispatchRequester::Model {
model_visible_call_id: "call-stdin".to_string(),
},
payload: ToolDispatchPayload::Function {
arguments: arguments.to_string(),
},
},
);
dispatch.record_failed("invalid arguments");
let rollout = replay_bundle(temp.path())?;
let call = &rollout.tool_calls["call-stdin"];
assert_eq!(call.execution.status, ExecutionStatus::Failed);
assert_eq!(call.terminal_operation_id, None);
assert!(rollout.terminal_operations.is_empty());
assert!(rollout.terminal_sessions.is_empty());
// The failed call still retains its original arguments and error.
for (id, expected) in [
(
call.raw_invocation_payload_id.as_ref().unwrap(),
json!({"tool_name": "write_stdin", "tool_namespace": null,
"payload": {"type": "function", "arguments": arguments}}),
),
(
call.raw_result_payload_id.as_ref().unwrap(),
json!({"type": "error", "error": "invalid arguments"}),
),
] {
let payload = std::fs::read(temp.path().join(&rollout.raw_payloads[id].path))?;
assert_eq!(
serde_json::from_slice::<serde_json::Value>(&payload)?,
expected
);
}
}
Ok(())
}
#[test]
fn code_mode_write_stdin_result_projects_structured_exec_fields() -> anyhow::Result<()> {
let temp = TempDir::new()?;
let writer = create_started_writer(&temp)?;
start_turn(&writer, "turn-1")?;
let request_payload = writer.write_json_payload(
RawPayloadKind::ToolInvocation,
&json!({
"tool_name": "write_stdin",
"tool_namespace": null,
"payload": {
"type": "function",
"arguments": json!({
"session_id": 456,
"chars": "",
"yield_time_ms": 1000,
"max_output_tokens": 4000
}).to_string()
}
}),
)?;
let response_payload = writer.write_json_payload(
RawPayloadKind::ToolResult,
&json!({
"type": "code_mode_response",
"value": {
"chunk_id": "abc123",
"wall_time_seconds": 1.25,
"exit_code": 0,
"original_token_count": 3,
"output": "done\n"
}
}),
)?;
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::CodeCellStarted {
runtime_cell_id: "cell-1".to_string(),
model_visible_call_id: "call-code".to_string(),
source_js: "await tools.write_stdin({ chars: '' })".to_string(),
},
)?;
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "tool-stdin".to_string(),
model_visible_call_id: None,
code_mode_runtime_tool_id: Some("runtime-tool-1".to_string()),
requester: crate::raw_event::RawToolCallRequester::CodeCell {
runtime_cell_id: "cell-1".to_string(),
},
kind: ToolCallKind::WriteStdin,
summary: generic_summary("write_stdin"),
invocation_payload: Some(request_payload),
},
)?;
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallEnded {
tool_call_id: "tool-stdin".to_string(),
status: ExecutionStatus::Completed,
result_payload: Some(response_payload),
},
)?;
let rollout = replay_bundle(temp.path())?;
assert_eq!(
rollout.terminal_operations["terminal_operation:1"].result,
Some(TerminalResult {
exit_code: Some(0),
stdout: "done\n".to_string(),
stderr: String::new(),
formatted_output: Some("done\n".to_string()),
original_token_count: Some(3),
chunk_id: Some("abc123".to_string()),
}),
);
Ok(())
}
fn append_inference_with_tool_call(writer: &TraceWriter) -> anyhow::Result<()> {
let request = writer.write_json_payload(
RawPayloadKind::InferenceRequest,
&json!({
"input": [message("user", "run tests")]
}),
)?;
writer.append(RawTraceEventPayload::InferenceStarted {
inference_call_id: "inference-1".to_string(),
thread_id: "thread-root".to_string(),
codex_turn_id: "turn-1".to_string(),
model: "gpt-test".to_string(),
provider_name: "test-provider".to_string(),
request_payload: request,
})?;
let response = writer.write_json_payload(
RawPayloadKind::InferenceResponse,
&json!({
"response_id": "resp-1",
"output_items": [{
"type": "function_call",
"name": "exec_command",
"arguments": "{\"cmd\":\"cargo test\"}",
"call_id": "call-1"
}]
}),
)?;
writer.append(RawTraceEventPayload::InferenceCompleted {
inference_call_id: "inference-1".to_string(),
response_id: Some("resp-1".to_string()),
upstream_request_id: None,
response_payload: response,
})?;
Ok(())
}
fn append_followup_with_tool_output(writer: &TraceWriter) -> anyhow::Result<()> {
let request = writer.write_json_payload(
RawPayloadKind::InferenceRequest,
&json!({
"previous_response_id": "resp-1",
"input": [{
"type": "function_call_output",
"call_id": "call-1",
"output": "ok\n"
}]
}),
)?;
writer.append(RawTraceEventPayload::InferenceStarted {
inference_call_id: "inference-2".to_string(),
thread_id: "thread-root".to_string(),
codex_turn_id: "turn-2".to_string(),
model: "gpt-test".to_string(),
provider_name: "test-provider".to_string(),
request_payload: request,
})?;
Ok(())
}