Use a shared ToolCallId for dispatched tool invocations (#62888)

## Why

Dispatched invocations, model-visible Responses calls, and Code Mode's
per-cell runtime calls use IDs with different roles. A dedicated Rust type
makes the dispatch identity explicit in APIs that carry it.

## What changed

Add `codex-tool-call-id` and use its `ToolCallId` across core tool dispatch,
nested Code Mode calls, and rollout tracing. The type wraps a string and
continues to serialize as a string.

GitOrigin-RevId: 119de57a9af840c4de72895adc9acdd0ed15b4fd
This commit is contained in:
cassirer-openai
2026-11-21 03:14:33 +00:00
committed by copyberry
parent 7edf91b13c
commit 8a1a476659
78 changed files with 402 additions and 286 deletions
+9
View File
@@ -3119,6 +3119,7 @@ dependencies = [
"codex-thread-context-ids",
"codex-thread-context-ids-test-support",
"codex-thread-store",
"codex-tool-call-id",
"codex-tools",
"codex-user-input",
"codex-utils-absolute-path",
@@ -4972,6 +4973,7 @@ dependencies = [
"anyhow",
"codex-code-mode",
"codex-protocol",
"codex-tool-call-id",
"http 1.4.0",
"pretty_assertions",
"serde",
@@ -5272,6 +5274,13 @@ dependencies = [
"zstd 0.13.3",
]
[[package]]
name = "codex-tool-call-id"
version = "0.0.0"
dependencies = [
"serde",
]
[[package]]
name = "codex-tools"
version = "0.0.0"
+2
View File
@@ -121,6 +121,7 @@ members = [
"tui",
"user-input",
"user-verification",
"tool-call-id",
"tools",
"v8-poc",
"websocket-auth",
@@ -312,6 +313,7 @@ codex-test-binary-support = { path = "test-binary-support" }
codex-thread-context-ids = { path = "thread-context-ids" }
codex-thread-context-ids-test-support = { path = "thread-context-ids/tests/support" }
codex-thread-store = { path = "thread-store" }
codex-tool-call-id = { path = "tool-call-id" }
codex-tools = { path = "tools" }
codex-tcp-tunnel = { path = "tcp-tunnel" }
codex-tui = { path = "tui" }
+1
View File
@@ -73,6 +73,7 @@ codex-skills-extension = { workspace = true }
codex-state = { workspace = true }
codex-terminal-detection = { workspace = true }
codex-thread-store = { workspace = true }
codex-tool-call-id = { workspace = true }
codex-tools = { workspace = true }
codex-user-input = { workspace = true }
codex-utils-absolute-path = { workspace = true }
+2 -1
View File
@@ -25,6 +25,7 @@ use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::TokenUsage;
use codex_protocol::turn_input::TurnStartOptions;
use codex_rollout_trace::ThreadTraceContext;
use codex_tool_call_id::ToolCallId;
use codex_user_input::ResolvedUserInput;
use futures::future::BoxFuture;
@@ -211,7 +212,7 @@ pub enum AgentInput {
message: AgentMessage,
mode: MessageDeliveryMode,
/// Native tool invocation to link when the recipient commits this message to history.
source_tool_call_id: Option<String>,
source_tool_call_id: Option<ToolCallId>,
},
}
+1 -1
View File
@@ -1818,7 +1818,7 @@ async fn cold_resume_with_thread_instructions_preserves_lazy_v2_child_inheritanc
step_context: issuing_step,
cancellation_token: CancellationToken::new(),
tracker: Default::default(),
call_id: "queue-only-cold-load".to_string(),
call_id: "queue-only-cold-load".into(),
tool_name: codex_tools::ToolName::plain("send_message"),
source: ToolCallSource::DirectPlaintextMessage,
payload: ToolPayload::Function {
+4 -3
View File
@@ -6,6 +6,7 @@ use codex_extension_api::MessageLifecycleContributor;
use codex_extension_api::MessageLifecycleInput;
use codex_protocol::ThreadId;
use codex_protocol::protocol::InterAgentCommunication;
use codex_tool_call_id::ToolCallId;
use serde::Deserialize;
use serde::Serialize;
use std::borrow::Cow;
@@ -46,7 +47,7 @@ impl AgentCommunicationKind {
pub(crate) struct AgentCommunicationContext {
pub(crate) kind: AgentCommunicationKind,
pub(crate) sender_thread_id: ThreadId,
pub(crate) source_tool_call_id: Option<String>,
pub(crate) source_tool_call_id: Option<ToolCallId>,
}
impl AgentCommunicationContext {
@@ -177,14 +178,14 @@ struct MessagePublication {
/// Clones follow one logical delivery through queues and share its consumption state.
#[derive(Clone)]
pub(crate) struct MessageDelivery {
pub(crate) source_tool_call_id: Option<String>,
pub(crate) source_tool_call_id: Option<ToolCallId>,
publication: Option<Arc<Mutex<Option<MessagePublication>>>>,
}
impl MessageDelivery {
pub(crate) fn publish(
sender: ThreadId,
source_tool_call_id: Option<String>,
source_tool_call_id: Option<ToolCallId>,
observers: &[Arc<dyn MessageLifecycleContributor>],
unconfirmed_results: Option<&Arc<AtomicUsize>>,
) -> Option<Self> {
+1 -1
View File
@@ -579,7 +579,7 @@ async fn responses_request_includes_internal_metadata_for_provider_grant_or_firs
for id in ["first", "second"] {
let call = ToolCall {
tool_name: codex_tools::ToolName::plain("mcp__apps__read"),
call_id: id.to_string(),
call_id: id.into(),
payload: ToolPayload::Function {
arguments: json!({"query": id}).to_string(),
},
+1 -1
View File
@@ -98,7 +98,7 @@ async fn local_compaction_retries_preserve_instructions_and_tool_metadata(
recorder.record_tool_call(
&ToolCall {
tool_name: ToolName::plain("nested_tool"),
call_id: "nested".to_string(),
call_id: "nested".into(),
payload: ToolPayload::Function {
arguments: "{}".to_string(),
},
@@ -248,7 +248,7 @@ pub(crate) async fn review_tool_call(
other => CodexErr::Fatal(format!("Guardian assessment failed: {other:?}")),
})?;
Ok(GuardianReviewResult {
call_id: invocation.call_id,
call_id: invocation.call_id.into(),
assessment,
})
};
+1 -1
View File
@@ -2733,7 +2733,7 @@ async fn guardian_review_retries_two_parse_failures_then_approves() -> anyhow::R
tracker: Arc::new(tokio::sync::Mutex::new(
crate::turn_diff_tracker::TurnDiffTracker::new(),
)),
call_id: "action".to_owned(),
call_id: "action".into(),
tool_name: codex_tools::ToolName::namespaced("team", "send_message"),
source: crate::tools::context::ToolCallSource::Direct,
native_call: Some(native_call),
+14 -13
View File
@@ -97,6 +97,7 @@ use codex_protocol::request_user_input::RequestUserInputResponse;
use codex_rmcp_client::ElicitationAction;
use codex_rmcp_client::ElicitationResponse;
use codex_rollout::state_db;
use codex_tool_call_id::ToolCallId;
use codex_tools::ToolName;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_output_truncation::TruncationPolicy;
@@ -161,7 +162,7 @@ pub(crate) async fn handle_mcp_tool_call(
sess: Arc<Session>,
step_context: &Arc<StepContext>,
cancellation_token: &CancellationToken,
call_id: String,
call_id: &ToolCallId,
originating_call: Option<ToolCallOrigin>,
advertised_tool: &ToolInfo,
prepared_call: anyhow::Result<PreparedMcpCall>,
@@ -226,7 +227,7 @@ pub(crate) async fn handle_mcp_tool_call(
let result = notify_mcp_tool_call_skip(
sess.as_ref(),
turn_context.as_ref(),
&call_id,
call_id,
invocation,
item_metadata,
format!("{error:#}"),
@@ -246,7 +247,7 @@ pub(crate) async fn handle_mcp_tool_call(
let result = notify_mcp_tool_call_skip(
sess.as_ref(),
turn_context.as_ref(),
&call_id,
call_id,
invocation,
item_metadata.clone(),
"MCP tool call blocked by app configuration".to_string(),
@@ -272,7 +273,7 @@ pub(crate) async fn handle_mcp_tool_call(
};
let requested_reviewer = sess.mcp_requested_reviewer(&step_context.settings).await;
let approval_context = sess.register_mcp_tool_approval_metadata(
&call_id,
call_id,
prepared_call.server_key(),
&invocation,
metadata,
@@ -284,7 +285,7 @@ pub(crate) async fn handle_mcp_tool_call(
notify_mcp_tool_call_started(
sess.as_ref(),
turn_context.as_ref(),
&call_id,
call_id,
invocation.clone(),
item_metadata.clone(),
)
@@ -294,7 +295,7 @@ pub(crate) async fn handle_mcp_tool_call(
&sess,
step_context,
cancellation_token,
&call_id,
call_id,
&invocation,
&invocation_tool_name,
&hook_tool_name,
@@ -319,7 +320,7 @@ pub(crate) async fn handle_mcp_tool_call(
return handle_approved_mcp_tool_call(
&sess,
step_context.as_ref(),
&call_id,
call_id,
originating_call.as_ref(),
invocation,
prepared_call,
@@ -338,7 +339,7 @@ pub(crate) async fn handle_mcp_tool_call(
notify_mcp_tool_call_skip(
sess.as_ref(),
turn_context.as_ref(),
&call_id,
call_id,
invocation,
item_metadata.clone(),
rejection,
@@ -350,7 +351,7 @@ pub(crate) async fn handle_mcp_tool_call(
notify_mcp_tool_call_skip(
sess.as_ref(),
turn_context.as_ref(),
&call_id,
call_id,
invocation,
item_metadata.clone(),
ResolvedModelMessages::from_model(turn_context.model_info())
@@ -379,7 +380,7 @@ pub(crate) async fn handle_mcp_tool_call(
notify_mcp_tool_call_skip(
sess.as_ref(),
turn_context.as_ref(),
&call_id,
call_id,
invocation,
item_metadata.clone(),
message,
@@ -412,7 +413,7 @@ pub(crate) async fn handle_mcp_tool_call(
handle_approved_mcp_tool_call(
&sess,
step_context.as_ref(),
&call_id,
call_id,
originating_call.as_ref(),
invocation,
prepared_call,
@@ -484,7 +485,7 @@ impl McpToolCallItemMetadata {
async fn handle_approved_mcp_tool_call(
sess: &Arc<Session>,
step_context: &StepContext,
call_id: &str,
call_id: &ToolCallId,
originating_call: Option<&ToolCallOrigin>,
invocation: McpInvocation,
prepared_call: PreparedMcpCall,
@@ -2881,7 +2882,7 @@ fn requires_mcp_tool_approval_for_mode(
async fn notify_mcp_tool_call_skip(
sess: &Session,
turn_context: &TurnContext,
call_id: &str,
call_id: &ToolCallId,
invocation: McpInvocation,
item_metadata: McpToolCallItemMetadata,
message: String,
+1 -1
View File
@@ -4830,7 +4830,7 @@ impl Session {
communication
.delivery
.as_ref()
.and_then(|d| d.source_tool_call_id.as_deref()),
.and_then(|d| d.source_tool_call_id.as_ref()),
);
}
if let Some(delivery) = delivery.take() {
+3 -3
View File
@@ -7653,7 +7653,7 @@ async fn request_permissions_tool_resolves_legacy_paths_against_selected_environ
turn: turn_context,
cancellation_token: CancellationToken::new(),
tracker,
call_id,
call_id: call_id.into(),
tool_name: codex_tools::ToolName::plain("request_permissions"),
source: ToolCallSource::Direct,
native_call: None,
@@ -7739,7 +7739,7 @@ async fn request_permissions_tool_rejects_invalid_requests(
turn: turn_context,
cancellation_token: CancellationToken::new(),
tracker: Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::new())),
call_id: "call-1".to_string(),
call_id: "call-1".into(),
tool_name: codex_tools::ToolName::plain("request_permissions"),
source: ToolCallSource::Direct,
native_call: None,
@@ -13255,7 +13255,7 @@ async fn unified_exec_rejects_escalated_permissions_when_policy_not_on_request()
step_context,
cancellation_token: CancellationToken::new(),
tracker: Arc::clone(&tracker),
call_id: "exec-call".to_string(),
call_id: "exec-call".into(),
tool_name: codex_tools::ToolName::plain("exec_command"),
source: crate::tools::context::ToolCallSource::Direct,
native_call: None,
@@ -616,7 +616,7 @@ async fn guardian_allows_exec_command_additional_permissions_requests_past_polic
step_context,
cancellation_token: CancellationToken::new(),
tracker: Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::new())),
call_id: "test-call".to_string(),
call_id: "test-call".into(),
tool_name: codex_tools::ToolName::plain("exec_command"),
source: crate::tools::context::ToolCallSource::Direct,
native_call: None,
@@ -742,7 +742,7 @@ async fn strict_auto_review_turn_grant_forces_guardian_for_exec_command_policy_s
step_context,
cancellation_token: CancellationToken::new(),
tracker: Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::new())),
call_id: "strict-shell-command-call".to_string(),
call_id: "strict-shell-command-call".into(),
tool_name: codex_tools::ToolName::plain("exec_command"),
source: ToolCallSource::Direct,
native_call: None,
@@ -896,7 +896,7 @@ async fn delayed_exec_command_uses_its_captured_authority_after_next_turn_starts
step_context,
cancellation_token: CancellationToken::new(),
tracker: Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::new())),
call_id: call_id.to_string(),
call_id: call_id.into(),
tool_name: codex_tools::ToolName::plain("exec_command"),
source: ToolCallSource::Direct,
native_call: None,
@@ -1104,7 +1104,7 @@ async fn guardian_allows_unified_exec_additional_permissions_requests_past_polic
step_context,
cancellation_token: CancellationToken::new(),
tracker: Arc::clone(&tracker),
call_id: "exec-call".to_string(),
call_id: "exec-call".into(),
tool_name: codex_tools::ToolName::plain("exec_command"),
source: crate::tools::context::ToolCallSource::Direct,
native_call: None,
@@ -1230,7 +1230,7 @@ async fn exec_command_allows_sticky_turn_permissions_without_inline_request_perm
step_context,
cancellation_token: CancellationToken::new(),
tracker: Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::new())),
call_id: "sticky-turn-grant".to_string(),
call_id: "sticky-turn-grant".into(),
tool_name: codex_tools::ToolName::plain("exec_command"),
source: crate::tools::context::ToolCallSource::Direct,
native_call: None,
+3 -2
View File
@@ -27,6 +27,7 @@ use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::protocol::MultiAgentVersion;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
use codex_tool_call_id::ToolCallId;
/// Child creation options; omitted overrides retain native MAv2 inheritance and role rules.
pub struct ThreadCreateRequest {
@@ -99,7 +100,7 @@ pub enum ThreadSpawnError {
pub(crate) async fn spawn(
session: &Session,
step_context: &StepContext,
call_id: &str,
call_id: &ToolCallId,
request: ThreadSpawnRequest,
) -> Result<ThreadSpawnResult, ThreadSpawnError> {
let (request, message) = request.into_parts()?;
@@ -114,7 +115,7 @@ pub(crate) async fn spawn(
.services
.rollout_thread_trace
.is_enabled()
.then(|| call_id.to_owned()),
.then(|| call_id.clone()),
},
source: settings.source,
options: settings.options,
@@ -14,6 +14,7 @@ use codex_history::ResponseItemEnvelope;
use codex_protocol::ThreadId;
use codex_protocol::models::FunctionCallOutputPayload;
use codex_protocol::models::ResponseItem;
use codex_tool_call_id::ToolCallId;
use codex_utils_output_truncation::with_serialization_allowance;
use serde_json::Value as JsonValue;
use tokio::sync::oneshot;
@@ -320,7 +321,7 @@ impl CodeModeSessionDelegate for CodeModeCellDelegate {
cancellation_token: CancellationToken,
) -> ToolInvocationFuture<'a> {
Box::pin(async move {
let call_id = format!("{PUBLIC_TOOL_NAME}-{}", uuid::Uuid::new_v4());
let call_id = ToolCallId::from(format!("{PUBLIC_TOOL_NAME}-{}", uuid::Uuid::new_v4()));
call_trace::received(
self.broker.thread_id,
&invocation.tool_name,
@@ -446,7 +447,7 @@ impl CoreTurnHost {
&self,
invocation: CodeModeNestedToolCall,
step_context: Arc<StepContext>,
call_id: String,
call_id: ToolCallId,
cancellation_token: CancellationToken,
) -> impl std::future::Future<Output = Result<JsonValue, String>> + Send + 'static {
let invocation = submit_nested_tool(
@@ -231,7 +231,7 @@ impl CodeModeExecuteHandler {
.execute(
session,
step_context,
call_id,
call_id.into(),
originating_call,
input,
&mut telemetry,
+3 -2
View File
@@ -23,6 +23,7 @@ use codex_code_mode::CodeModeToolKind;
use codex_code_mode::RuntimeResponse;
use codex_protocol::ThreadId;
use codex_protocol::models::FunctionCallOutputContentItem;
use codex_tool_call_id::ToolCallId;
use futures::future::join_all;
use serde_json::Value as JsonValue;
use tokio::sync::OnceCell;
@@ -354,7 +355,7 @@ fn submit_nested_tool(
step_context: Arc<StepContext>,
tool_runtime: ToolCallRuntime,
invocation: CodeModeNestedToolCall,
call_id: String,
call_id: ToolCallId,
cancellation_token: CancellationToken,
) -> Result<
impl std::future::Future<Output = Result<JsonValue, FunctionCallError>> + Send + 'static,
@@ -419,7 +420,7 @@ fn submit_nested_tool(
.track_code_mode_tool_call(codex_analytics::CodeModeToolCallFact::ChildStarted {
thread_id: session.thread_id.to_string(),
turn_id: step_context.turn.sub_id.clone(),
call_id: call.call_id.clone(),
call_id: call.call_id.to_string(),
cell_id: cell_id.to_string(),
});
let result = tool_runtime.handle_tool_call_with_source(
@@ -5,6 +5,7 @@ use codex_analytics::CodeModeToolCallFact;
use codex_analytics::CodeModeToolCallStatus;
use codex_analytics::TurnAnalyticsMetadata;
use codex_protocol::ThreadId;
use codex_tool_call_id::ToolCallId;
use std::sync::Arc;
use std::time::Duration;
use tracing::Span;
@@ -14,7 +15,7 @@ pub(super) struct CodeModeToolCallGuard {
thread_id: String,
turn_id: String,
turn_metadata: Arc<dyn TurnAnalyticsMetadata>,
call_id: String,
call_id: ToolCallId,
pub(super) cell_id: Option<String>,
tool_name: &'static str,
started_at_ms: u64,
@@ -28,7 +29,7 @@ impl CodeModeToolCallGuard {
session: &crate::session::session::Session,
turn_id: String,
turn_metadata: Arc<dyn TurnAnalyticsMetadata>,
call_id: String,
call_id: ToolCallId,
tool_name: &'static str,
handler_span: Span,
) -> Self {
@@ -111,7 +112,7 @@ impl Drop for CodeModeToolCallGuard {
thread_id: self.thread_id.clone(),
turn_id: self.turn_id.clone(),
turn_metadata: self.turn_metadata.clone(),
call_id: self.call_id.clone(),
call_id: self.call_id.to_string(),
cell_id: self.cell_id.clone(),
tool_name: self.tool_name.to_string(),
started_at_ms: self.started_at_ms,
@@ -123,13 +124,13 @@ impl Drop for CodeModeToolCallGuard {
pub(super) struct NestedToolDispatchTrace {
thread_id: ThreadId,
pub(super) call_id: String,
pub(super) call_id: ToolCallId,
pub(super) interruption: Option<DispatchInterruption>,
pub(super) span: Span,
}
impl NestedToolDispatchTrace {
pub(super) fn new(thread_id: ThreadId, call_id: String) -> Self {
pub(super) fn new(thread_id: ThreadId, call_id: ToolCallId) -> Self {
Self {
thread_id,
call_id,
+3 -2
View File
@@ -17,6 +17,7 @@ use codex_protocol::models::ResponseInputItem;
use codex_protocol::models::ResponseItem;
use codex_protocol::models::ToolResultMetadata;
use codex_protocol::models::function_call_output_content_items_to_text;
use codex_tool_call_id::ToolCallId;
use codex_tools::LoadableToolSpec;
use codex_tools::ToolName;
use codex_utils_audio::estimate_tool_audio_tokens;
@@ -118,7 +119,7 @@ pub struct ToolInvocation {
pub(crate) step_context: Arc<StepContext>,
pub cancellation_token: CancellationToken,
pub tracker: SharedTurnDiffTracker,
pub call_id: String,
pub call_id: ToolCallId,
pub tool_name: ToolName,
pub source: ToolCallSource,
pub payload: ToolPayload,
@@ -157,7 +158,7 @@ impl ToolInvocation {
.find_map(|item| match item {
ResponseItem::FunctionCall { id, call_id, .. }
| ResponseItem::CustomToolCall { id, call_id, .. }
if call_id == &self.call_id =>
if call_id == self.call_id.as_str() =>
{
id.clone()
}
@@ -37,7 +37,7 @@ impl Drop for ControlToolCallGuard<'_> {
thread_id: invocation.session.thread_id.to_string(),
turn_id: invocation.turn.sub_id.clone(),
turn_metadata: invocation.turn.turn_metadata_state.clone(),
call_id: invocation.call_id.clone(),
call_id: invocation.call_id.to_string(),
cell_id: match &invocation.source {
ToolCallSource::CodeMode { cell_id, .. } => Some(cell_id.clone()),
ToolCallSource::Direct | ToolCallSource::DirectPlaintextMessage => None,
@@ -33,6 +33,7 @@ use codex_protocol::models::ToolResultMetadata;
use codex_protocol::models::executed_tool_call_metadata_bytes;
use codex_protocol::models::normalize_executed_tool_call_completeness;
use codex_protocol::openai_models::ToolMode;
use codex_tool_call_id::ToolCallId;
use indexmap::IndexMap;
use serde_json::Value as JsonValue;
use uuid::Uuid;
@@ -266,7 +267,7 @@ struct ExecutedToolCallRecorderState {
// Keep nested IDs separate so this conservative filter cannot change existing completeness.
seen_nested_ids: SeenIds,
can_prove_wait_completion: bool,
pending_wrapper_origins: HashSet<String>,
pending_wrapper_origins: HashSet<ToolCallId>,
}
/// Keep each output's calls and completion marker together through replay and pruning.
@@ -278,9 +279,9 @@ struct RetainedToolCalls {
cell_id: Option<String>,
runtime_cell_id: Option<CellId>,
// Invocation IDs stay local and are retained only with their original output's calls.
call_index_by_id: HashMap<String, usize>,
call_index_by_id: HashMap<ToolCallId, usize>,
// Track newly backfilled metadata separately from pre-existing observations.
truncated_call_index_by_id: HashMap<String, usize>,
truncated_call_index_by_id: HashMap<ToolCallId, usize>,
late_truncated_indices: HashSet<usize>,
result_metadata_updated: bool,
}
@@ -319,7 +320,7 @@ enum CellCompletion {
#[derive(Default)]
struct RecordedCell {
output_item_id: Option<ResponseItemId>,
pending_calls: IndexMap<String, ExecutedToolCall>,
pending_calls: IndexMap<ToolCallId, ExecutedToolCall>,
completion: CellCompletion,
originating_call_id: Option<String>,
truncated_metadata_binding_valid: bool,
@@ -784,7 +785,7 @@ impl ExecutedToolCalls {
pub(crate) fn record_accepted_result(
&self,
source: &ToolCallSource,
call_id: &str,
call_id: &ToolCallId,
result: &dyn ToolOutput,
) {
if !matches!(source, ToolCallSource::CodeMode { .. }) {
@@ -841,7 +842,7 @@ impl ExecutedToolCalls {
fn record_nested_tool_call(
&self,
cell_id: CellId,
call_id: String,
call_id: ToolCallId,
call: ExecutedToolCall,
original_bytes: usize,
) {
@@ -906,7 +907,7 @@ impl ExecutedToolCalls {
fn record_result_metadata(
&self,
source: &ToolCallSource,
call_id: &str,
call_id: &ToolCallId,
metadata: ToolResultMetadata,
) -> bool {
let ToolCallSource::CodeMode { cell_id, .. } = source else {
@@ -19,7 +19,7 @@ impl ExecutedToolCalls {
call_id: &str,
metadata: &JsonValue,
) -> bool {
self.record_result_metadata(source, call_id, ToolResultMetadata::new(metadata))
self.record_result_metadata(source, &call_id.into(), ToolResultMetadata::new(metadata))
}
fn attach_pending_to_prompt(
@@ -79,7 +79,7 @@ fn record_nested_call(
let call = ExecutedToolCall::new("nested_tool".to_string(), json!({}));
recorder.record_nested_tool_call(
cell.clone(),
call_id.to_string(),
call_id.into(),
call.clone(),
/*original_bytes*/ 2,
);
@@ -98,7 +98,7 @@ fn record_truncated_call(
);
recorder.record_nested_tool_call(
cell.clone(),
call_id.to_string(),
call_id.into(),
call.clone(),
/*original_bytes*/ 9_000,
);
@@ -117,7 +117,7 @@ fn selected_exec_result_uses_only_the_retained_wrapper_inventory() {
recorder.start_cell(&cell, "exec");
recorder.record_nested_tool_call(
cell.clone(),
"inner".to_owned(),
"inner".into(),
ExecutedToolCall::new("normalized-alias__lookup".to_owned(), json!({})),
/*original_bytes*/ 2,
);
@@ -221,7 +221,7 @@ async fn capture_only_request_metadata_preserves_late_bindings_and_restores_full
};
let output =
captured_mcp_output(&capture, json!({"content": [{"type": "text", "text": id}]}));
recorder.record_accepted_result(&source, id, &output);
recorder.record_accepted_result(&source, &id.into(), &output);
};
record("connector");
recorder.finish_cell_recording(&cell);
@@ -671,7 +671,7 @@ async fn recorder_refreshes_without_changing_execution_features_or_claiming_miss
let call = ToolCall {
tool_name: codex_tools::ToolName::plain("test_tool"),
call_id: format!("call-{index}"),
call_id: format!("call-{index}").into(),
payload: ToolPayload::Function {
arguments: r#"{"value":7}"#.to_string(),
},
@@ -735,7 +735,7 @@ async fn recorder_refreshes_without_changing_execution_features_or_claiming_miss
runtime_tool_call_id: "runtime-nested".to_string(),
};
let result = MetadataLookup(std::cell::Cell::new(0), json!({}), &calls);
calls.record_accepted_result(&source, "nested", &result);
calls.record_accepted_result(&source, &"nested".into(), &result);
assert_eq!(result.0.get(), usize::from(enabled));
nested.set_tool_result_metadata(ToolResultMetadata::new(&json!({})));
if enabled {
@@ -769,7 +769,7 @@ fn executed_tool_call_recorder_bounds_pending_calls_and_preserves_overflow() {
recorder.record_call(
&ToolCall {
tool_name: codex_tools::ToolName::plain(crate::tools::code_mode::PUBLIC_TOOL_NAME),
call_id: format!("failed-wrapper-{index}"),
call_id: format!("failed-wrapper-{index}").into(),
payload: ToolPayload::Custom {
input: "".to_string(),
},
@@ -786,7 +786,7 @@ fn executed_tool_call_recorder_bounds_pending_calls_and_preserves_overflow() {
for index in 0..MAX_PENDING_EXECUTED_TOOL_CALLS + 2 {
recorder.record_nested_tool_call(
cell_id.clone(),
format!("nested-{index}"),
format!("nested-{index}").into(),
ExecutedToolCall::new("nested_tool".to_string(), json!({})),
/*original_bytes*/ 2,
);
@@ -893,7 +893,7 @@ fn tool_call_completeness_requires_finished_lossless_recording() {
if scenario != "unfinished" {
recorder.record_nested_tool_call(
cell_id.clone(),
"nested-call".to_string(),
"nested-call".into(),
ExecutedToolCall::new("nested_tool".to_string(), json!({})),
/*original_bytes*/ 2,
);
@@ -1043,7 +1043,7 @@ fn tool_call_completeness_survives_waits_without_changing_deltas() {
tool_name: codex_tools::ToolName::plain(
crate::tools::code_mode::WAIT_TOOL_NAME,
),
call_id: call_id.to_string(),
call_id: call_id.into(),
payload: ToolPayload::Function {
arguments: json!({"cell_id": cell_id.as_str()}).to_string(),
},
@@ -1082,7 +1082,7 @@ fn tool_call_completeness_survives_waits_without_changing_deltas() {
};
recorder.record_nested_tool_call(
cell_id.clone(),
format!("nested-{index}"),
format!("nested-{index}").into(),
call.clone(),
original_bytes,
);
@@ -1311,7 +1311,7 @@ fn completeness_rejects_direct_id_collision_and_late_calls() {
recorder.record_call(
&ToolCall {
tool_name: codex_tools::ToolName::plain("direct_tool"),
call_id: "exec-collision".to_string(),
call_id: "exec-collision".into(),
payload: ToolPayload::Function {
arguments: "{}".to_string(),
},
@@ -1352,14 +1352,14 @@ fn large_wrapped_arguments_preserve_later_wait_completeness() {
});
let (call, original_bytes) = recorded_call(&ToolCall {
tool_name: codex_tools::ToolName::plain("nested_tool"),
call_id: "nested".to_string(),
call_id: "nested".into(),
payload: ToolPayload::Function {
arguments: arguments.to_string(),
},
encrypted_function_args: None,
native_call: None,
});
recorder.record_nested_tool_call(cell.clone(), "nested".to_string(), call, original_bytes);
recorder.record_nested_tool_call(cell.clone(), "nested".into(), call, original_bytes);
let mut initial = [exec_input("exec"), exec_output("exec")];
recorder.attach_to_prompt(&mut initial, &mut HashMap::new());
assert_eq!(
@@ -1414,7 +1414,7 @@ async fn nested_result_budget_reopens_after_binding_loss(invalidate_origin: bool
"content": [{"type": "text", "text": "x".repeat(text_bytes)}], "_meta": {"id": id}
}),
);
recorder.record_accepted_result(&source, id, &output);
recorder.record_accepted_result(&source, &id.into(), &output);
};
let bind = |id: &str, text_bytes: usize| {
let cell = CellId::new(id.to_string());
@@ -1481,7 +1481,7 @@ async fn result_metadata_updates_the_exact_retained_call_and_preserves_large_ret
for call_id in ["first", "second"] {
recorder.record_nested_tool_call(
cell_id.clone(),
call_id.to_string(),
call_id.into(),
call.clone(),
/*original_bytes*/ 2,
);
@@ -1511,7 +1511,7 @@ async fn result_metadata_updates_the_exact_retained_call_and_preserves_large_ret
let json = json!({"content": [{"type": "text", "text": "private".repeat(80 * 1024)}]});
for id in ["unknown", "second"] {
let output = captured_mcp_output(&capture, json.clone());
recorder.record_accepted_result(&source(cell_id.as_str()), id, &output);
recorder.record_accepted_result(&source(cell_id.as_str()), &id.into(), &output);
}
assert!(recorder.attach_pending_to_prompt(&mut history, &mut retry_cache));
let bodies = capture.for_input(&history, &turn.auth_manager.as_ref().unwrap().auth_owner());
@@ -1567,7 +1567,7 @@ fn late_result_metadata_survives_truncated_arguments() {
/*max_bytes*/ 8_192,
);
for (id, call, bytes) in [("first", &first, 9_000), ("second", &second, 9_001)] {
recorder.record_nested_tool_call(cell.clone(), id.to_string(), call.clone(), bytes);
recorder.record_nested_tool_call(cell.clone(), id.into(), call.clone(), bytes);
}
let history = [exec_input("exec"), exec_output("exec")];
let mut retry_cache = HashMap::new();
@@ -1839,7 +1839,7 @@ fn late_truncated_metadata_is_not_attached_to_ambiguous_outputs() {
"duplicate_id" => {
recorder.record_nested_tool_call(
cell.clone(),
"nested".to_string(),
"nested".into(),
call,
/*original_bytes*/ 9_000,
);
@@ -1926,17 +1926,12 @@ fn late_truncated_metadata_with_wrapped_arguments_rejects_ambiguous_outputs() {
.to_string();
let (wrapped_call, original_bytes) = recorded_call(&ToolCall {
tool_name: codex_tools::ToolName::plain("other"),
call_id: "other".to_string(),
call_id: "other".into(),
payload: ToolPayload::Function { arguments },
encrypted_function_args: None,
native_call: None,
});
recorder.record_nested_tool_call(
cell.clone(),
"other".to_string(),
wrapped_call,
original_bytes,
);
recorder.record_nested_tool_call(cell.clone(), "other".into(), wrapped_call, original_bytes);
let history = [exec_input("exec"), exec_output("exec")];
let mut retry_cache = HashMap::new();
let mut initial = history.clone();
@@ -2035,7 +2030,7 @@ fn finished_cells_without_more_waits_do_not_block_new_calls() {
recorder.start_cell(&cell, cell.as_str());
recorder.record_nested_tool_call(
cell.clone(),
format!("nested-{index}"),
format!("nested-{index}").into(),
call.clone(),
/*original_bytes*/ 2,
);
@@ -2049,7 +2044,7 @@ fn finished_cells_without_more_waits_do_not_block_new_calls() {
recorder.start_cell(&fresh, "fresh-output");
recorder.record_nested_tool_call(
fresh.clone(),
"fresh-call".to_string(),
"fresh-call".into(),
call.clone(),
/*original_bytes*/ 2,
);
@@ -445,7 +445,7 @@ async fn direct_pending_limit_releases_on_completion_or_dropped_future() {
let recorder = ExecutedToolCalls::new(&features, &InitialHistory::New);
let call = ToolCall {
tool_name: codex_tools::ToolName::plain("test_tool"),
call_id: "direct".to_string(),
call_id: "direct".into(),
payload: ToolPayload::Function {
arguments: json!({ "argument": "kept" }).to_string(),
},
@@ -524,7 +524,7 @@ async fn direct_recording_preserves_encoded_arguments_in_history() {
assert!(wire_bytes > 8 * 1024);
let call = ToolCall {
tool_name: codex_tools::ToolName::plain("test_tool"),
call_id: "direct".to_string(),
call_id: "direct".into(),
payload: ToolPayload::Function {
arguments: invalid_json.clone(),
},
@@ -329,7 +329,7 @@ impl ApplyPatchHandler {
session,
step_context,
cancellation_token,
call_id,
call_id: call_id.into(),
tool_name,
};
let content = execute_prepared_patch(request, Some(&tracker), tool_ctx).await?;
@@ -410,7 +410,7 @@ impl CoreToolRuntime for ApplyPatchHandler {
Some(PostToolUsePayload {
tool_cwd: result.post_tool_use_cwd(),
tool_name: HookToolName::apply_patch(),
tool_use_id: invocation.call_id.clone(),
tool_use_id: invocation.call_id.to_string(),
tool_input: serde_json::json!({
"command": apply_patch_payload_command(&invocation.payload)?,
}),
@@ -51,7 +51,7 @@ async fn invocation_for_payload(payload: ToolPayload) -> ToolInvocation {
turn,
cancellation_token: tokio_util::sync::CancellationToken::new(),
tracker: Arc::new(Mutex::new(TurnDiffTracker::new())),
call_id: "call-apply-patch".to_string(),
call_id: "call-apply-patch".into(),
tool_name: codex_tools::ToolName::plain("apply_patch"),
source: crate::tools::context::ToolCallSource::Direct,
payload,
+1 -1
View File
@@ -146,7 +146,7 @@ impl DynamicToolHandler {
let response = request_dynamic_tool(
&session,
turn.as_ref(),
call_id,
call_id.into(),
self.tool_name.clone(),
args,
cancellation_token,
@@ -239,7 +239,7 @@ async fn to_extension_call<'a>(
.and_then(|metadata| to_ascii_json_string(&metadata).ok());
ExtensionToolCall {
turn_id: invocation.turn.sub_id.clone(),
call_id: invocation.call_id.clone(),
call_id: invocation.call_id.to_string(),
tool_name: invocation.tool_name.clone(),
model: settings.model_info.slug.clone(),
codex_turn_metadata,
@@ -429,7 +429,7 @@ mod tests {
turn,
cancellation_token: tokio_util::sync::CancellationToken::new(),
tracker: Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::new())),
call_id: "call-extension".to_string(),
call_id: "call-extension".into(),
tool_name: codex_tools::ToolName::plain("extension_echo"),
source: ToolCallSource::Direct,
native_call: None,
@@ -528,7 +528,7 @@ mod tests {
turn,
cancellation_token: tokio_util::sync::CancellationToken::new(),
tracker: Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::new())),
call_id: "call-extension".to_string(),
call_id: "call-extension".into(),
tool_name: codex_tools::ToolName::plain("extension_echo"),
source: ToolCallSource::CodeMode {
cell_id: "cell-1".to_string(),
+6 -6
View File
@@ -316,7 +316,7 @@ impl McpHandler {
Arc::clone(&session),
&step_context,
&cancellation_token,
call_id.clone(),
&call_id,
originating_call,
&self.definition.tool_info,
prepared_mcp_call,
@@ -594,7 +594,7 @@ impl CoreToolRuntime for McpHandler {
Some(PostToolUsePayload {
tool_cwd: result.post_tool_use_cwd(),
tool_name: self.hook_tool_name(),
tool_use_id: invocation.call_id.clone(),
tool_use_id: invocation.call_id.to_string(),
tool_input: result.post_tool_use_input(&invocation.payload)?,
tool_response,
})
@@ -745,7 +745,7 @@ mod tests {
turn,
cancellation_token: tokio_util::sync::CancellationToken::new(),
tracker: Arc::new(Mutex::new(TurnDiffTracker::new())),
call_id: "call-mcp-pre".to_string(),
call_id: "call-mcp-pre".into(),
tool_name: codex_tools::ToolName::namespaced("memory", "create_entities"),
source: ToolCallSource::Direct,
payload,
@@ -781,7 +781,7 @@ mod tests {
turn,
cancellation_token: tokio_util::sync::CancellationToken::new(),
tracker: Arc::new(Mutex::new(TurnDiffTracker::new())),
call_id: "call-mcp-pre-builtin-like".to_string(),
call_id: "call-mcp-pre-builtin-like".into(),
tool_name: codex_tools::ToolName::namespaced("mcp__foo", "exec_command"),
source: ToolCallSource::Direct,
payload,
@@ -813,7 +813,7 @@ mod tests {
turn,
cancellation_token: tokio_util::sync::CancellationToken::new(),
tracker: Arc::new(Mutex::new(TurnDiffTracker::new())),
call_id: "call-mcp-rewrite-builtin-like".to_string(),
call_id: "call-mcp-rewrite-builtin-like".into(),
tool_name: codex_tools::ToolName::namespaced("mcp__foo", "exec_command"),
source: ToolCallSource::Direct,
payload,
@@ -877,7 +877,7 @@ mod tests {
turn,
cancellation_token: tokio_util::sync::CancellationToken::new(),
tracker: Arc::new(Mutex::new(TurnDiffTracker::new())),
call_id: "call-mcp-post".to_string(),
call_id: "call-mcp-post".into(),
tool_name: codex_tools::ToolName::namespaced("filesystem", "read_file"),
source: ToolCallSource::Direct,
payload,
@@ -52,7 +52,7 @@ async fn handle_close_agent(
.emit_turn_item_started(
&turn,
&TurnItem::CollabAgentToolCall(CollabAgentToolCallItem {
id: call_id.clone(),
id: call_id.to_string(),
tool: CollabAgentTool::CloseAgent,
status: CollabAgentToolCallStatus::InProgress,
sender_thread_id: session.thread_id,
@@ -93,7 +93,7 @@ async fn handle_close_agent(
.emit_turn_item_completed(
&turn,
TurnItem::CollabAgentToolCall(CollabAgentToolCallItem {
id: call_id,
id: call_id.into(),
tool: CollabAgentTool::CloseAgent,
status: collab_tool_call_status(&status, Some(agent_id)),
sender_thread_id: session.thread_id,
@@ -64,7 +64,7 @@ async fn handle_resume_agent(
.emit_turn_item_started(
&turn,
&TurnItem::CollabAgentToolCall(CollabAgentToolCallItem {
id: call_id.clone(),
id: call_id.to_string(),
tool: CollabAgentTool::ResumeAgent,
status: CollabAgentToolCallStatus::InProgress,
sender_thread_id: session.thread_id,
@@ -109,7 +109,7 @@ async fn handle_resume_agent(
.emit_turn_item_completed(
&turn,
TurnItem::CollabAgentToolCall(CollabAgentToolCallItem {
id: call_id,
id: call_id.into(),
tool: CollabAgentTool::ResumeAgent,
status: collab_tool_call_status(&status, Some(receiver_thread_id)),
sender_thread_id: session.thread_id(),
@@ -86,7 +86,7 @@ impl Handler {
.emit_turn_item_started(
&turn,
&TurnItem::CollabAgentToolCall(CollabAgentToolCallItem {
id: call_id.clone(),
id: call_id.to_string(),
tool: CollabAgentTool::SendInput,
status: CollabAgentToolCallStatus::InProgress,
sender_thread_id: session.thread_id,
@@ -119,7 +119,7 @@ impl Handler {
.emit_turn_item_completed(
&turn,
TurnItem::CollabAgentToolCall(CollabAgentToolCallItem {
id: call_id,
id: call_id.into(),
tool: CollabAgentTool::SendInput,
status: collab_tool_call_status(&status, Some(receiver_thread_id)),
sender_thread_id: session.thread_id,
@@ -89,7 +89,7 @@ async fn handle_spawn_agent(
.emit_turn_item_started(
turn,
&TurnItem::CollabAgentToolCall(CollabAgentToolCallItem {
id: call_id.clone(),
id: call_id.to_string(),
tool: CollabAgentTool::SpawnAgent,
status: CollabAgentToolCallStatus::InProgress,
sender_thread_id: session.thread_id,
@@ -133,7 +133,7 @@ async fn handle_spawn_agent(
)?,
options: SpawnAgentOptions {
request_country: step_context.settings.request_country().clone(),
fork_parent_spawn_call_id: fork_mode.as_ref().map(|_| call_id.clone()),
fork_parent_spawn_call_id: fork_mode.as_ref().map(|_| call_id.to_string()),
fork_mode: fork_mode.clone(),
parent_thread_id: Some(session.thread_id),
parent_turn_id: Some(turn.sub_id.clone()),
@@ -199,7 +199,7 @@ async fn handle_spawn_agent(
.emit_turn_item_completed(
turn,
TurnItem::CollabAgentToolCall(CollabAgentToolCallItem {
id: call_id,
id: call_id.into(),
tool: CollabAgentTool::SpawnAgent,
status: collab_tool_call_status(&status, new_thread_id),
sender_thread_id: session.thread_id,
@@ -106,7 +106,7 @@ impl Handler {
.emit_turn_item_started(
&turn,
&TurnItem::CollabAgentToolCall(CollabAgentToolCallItem {
id: call_id.clone(),
id: call_id.to_string(),
tool: CollabAgentTool::Wait,
status: CollabAgentToolCallStatus::InProgress,
sender_thread_id: session.thread_id,
@@ -151,7 +151,7 @@ impl Handler {
.emit_turn_item_completed(
&turn,
TurnItem::CollabAgentToolCall(CollabAgentToolCallItem {
id: call_id.clone(),
id: call_id.to_string(),
tool: CollabAgentTool::Wait,
status: wait_tool_call_status(&statuses),
sender_thread_id: session.thread_id,
@@ -222,7 +222,7 @@ impl Handler {
.emit_turn_item_completed(
&turn,
TurnItem::CollabAgentToolCall(CollabAgentToolCallItem {
id: call_id,
id: call_id.into(),
tool: CollabAgentTool::Wait,
status: wait_tool_call_status(&statuses_by_id),
sender_thread_id: session.thread_id,
@@ -112,7 +112,7 @@ fn invocation(
turn,
cancellation_token: CancellationToken::new(),
tracker: Arc::new(Mutex::new(TurnDiffTracker::default())),
call_id: "call-1".to_string(),
call_id: "call-1".into(),
tool_name: codex_tools::ToolName::plain(tool_name),
source: crate::tools::context::ToolCallSource::Direct,
payload,
@@ -22,7 +22,7 @@ impl ToolCallAnalytics {
turn_id: invocation.turn.sub_id.clone(),
item: CollabAgentToolCallItem {
// Activity and analytics must use the same ID for turn-count deduplication.
id: invocation.call_id.clone(),
id: invocation.call_id.to_string(),
tool,
status: CollabAgentToolCallStatus::Interrupted,
sender_thread_id: invocation.session.thread_id,
@@ -73,7 +73,7 @@ async fn handle_interrupt_agent(
SubAgentActivityItem {
model: None,
reasoning_effort: None,
id: call_id,
id: call_id.into(),
agent_thread_id: agent_id,
agent_path,
kind: SubAgentActivityKind::Interrupted,
@@ -94,7 +94,7 @@ pub(super) async fn handle_message_string_tool(
SubAgentActivityItem {
model: None,
reasoning_effort: None,
id: call_id,
id: call_id.into(),
agent_thread_id: receiver_thread_id,
agent_path: receiver_agent_path,
kind: SubAgentActivityKind::Interacted,
@@ -49,7 +49,7 @@ impl ToolExecutor<ToolInvocation> for Handler {
let analytics = invocation.session.services.analytics_events_client.clone();
let sender_thread_id = invocation.session.thread_id;
let turn_id = invocation.step_context.turn.sub_id.clone();
let call_id = invocation.call_id.clone();
let call_id = invocation.call_id.to_string();
let started_at_ms = now_unix_timestamp_ms();
let result = handle_spawn_agent(invocation).await;
let completed_at_ms = now_unix_timestamp_ms();
@@ -165,7 +165,7 @@ async fn handle_spawn_agent(
SubAgentActivityItem {
model: Some(agent_snapshot.model.clone()),
reasoning_effort: agent_snapshot.reasoning_effort.clone(),
id: call_id,
id: call_id.into(),
agent_thread_id: new_thread_id,
agent_path: new_agent_path.clone(),
kind: SubAgentActivityKind::Started,
@@ -72,7 +72,7 @@ impl Handler {
.emit_turn_item_started(
&turn,
&TurnItem::CollabAgentToolCall(CollabAgentToolCallItem {
id: call_id.clone(),
id: call_id.to_string(),
tool: CollabAgentTool::Wait,
status: CollabAgentToolCallStatus::InProgress,
sender_thread_id: session.thread_id,
@@ -113,7 +113,7 @@ impl Handler {
.emit_turn_item_completed(
&turn,
TurnItem::CollabAgentToolCall(CollabAgentToolCallItem {
id: call_id,
id: call_id.into(),
tool: CollabAgentTool::Wait,
status: CollabAgentToolCallStatus::Completed,
sender_thread_id: session.thread_id,
@@ -131,7 +131,7 @@ impl RequestPermissionsHandler {
let response = session
.request_permissions_for_environment(
&step_context,
call_id,
call_id.into(),
request,
cancellation_token,
)
@@ -54,7 +54,7 @@ async fn request_plugin_install_rejects_restricted_threads(presentation: ToolSug
turn,
cancellation_token: tokio_util::sync::CancellationToken::new(),
tracker: Arc::new(Mutex::new(TurnDiffTracker::default())),
call_id: "call-1".to_string(),
call_id: "call-1".into(),
tool_name: codex_tools::ToolName::plain(REQUEST_PLUGIN_INSTALL_TOOL_NAME),
source: crate::tools::context::ToolCallSource::Direct,
native_call: None,
@@ -85,7 +85,7 @@ impl RequestUserInputHandler {
};
let questions = args.questions.clone();
let accepted = session
.request_user_input(turn.as_ref(), call_id.clone(), args)
.request_user_input(turn.as_ref(), call_id.to_string(), args)
.await
.ok_or_else(|| {
FunctionCallError::RespondToModel(format!(
@@ -136,7 +136,7 @@ impl RequestUserInputHandler {
.record_retained_context(RetainedContextEvent::VerifiedAnswer {
answer: VerifiedAnswer {
turn_id: turn.sub_id.clone(),
call_id,
call_id: call_id.into(),
questions: user_input,
},
acceptance_order: Some(accepted.acceptance_order),
@@ -130,7 +130,7 @@ impl ToolExecutor<ToolInvocation> for RequestUserInputAsyncHandler {
let item = TurnItem::AgentMessage(AgentMessageItem {
moderation: None,
id: call_id,
id: call_id.into(),
content: vec![AgentMessageContent::Text {
text: messages.join("\n\n"),
}],
@@ -36,7 +36,7 @@ async fn request_user_input_rejects_restricted_threads() {
turn,
cancellation_token: tokio_util::sync::CancellationToken::new(),
tracker: Arc::new(Mutex::new(TurnDiffTracker::default())),
call_id: "call-1".to_string(),
call_id: "call-1".into(),
tool_name: codex_tools::ToolName::plain(REQUEST_USER_INPUT_TOOL_NAME),
source: crate::tools::context::ToolCallSource::Direct,
native_call: None,
@@ -116,7 +116,7 @@ async fn request_user_input_sets_non_blocking_outside_plan_mode(
turn,
cancellation_token: tokio_util::sync::CancellationToken::new(),
tracker: Arc::new(Mutex::new(TurnDiffTracker::default())),
call_id: "call-1".to_string(),
call_id: "call-1".into(),
tool_name: codex_tools::ToolName::plain(REQUEST_USER_INPUT_TOOL_NAME),
source: crate::tools::context::ToolCallSource::Direct,
native_call: None,
@@ -239,7 +239,7 @@ async fn request_user_input_sets_blocking_from_turn_mode() {
turn,
cancellation_token: tokio_util::sync::CancellationToken::new(),
tracker: Arc::new(Mutex::new(TurnDiffTracker::default())),
call_id: "call-1".to_string(),
call_id: "call-1".into(),
tool_name: codex_tools::ToolName::plain(REQUEST_USER_INPUT_TOOL_NAME),
source: crate::tools::context::ToolCallSource::Direct,
native_call: None,
@@ -83,7 +83,7 @@ impl ToolExecutor<ToolInvocation> for SendMessageToUserAsyncHandler {
let item = TurnItem::AgentMessage(AgentMessageItem {
moderation: None,
id: call_id,
id: call_id.into(),
content: vec![AgentMessageContent::Text {
text: message.to_string(),
}],
+1 -1
View File
@@ -101,7 +101,7 @@ impl ToolExecutor<ToolInvocation> for SleepHandler {
let started = Instant::now();
let item = TurnItem::Extension(ExtensionItem::Sleep(SleepItem {
id: call_id,
id: call_id.into(),
duration_ms: args.duration_ms,
}));
session.emit_turn_item_started(turn.as_ref(), &item).await;
@@ -155,7 +155,7 @@ impl ExecCommandHandler {
session.clone(),
step_context.clone(),
cancellation_token,
call_id.clone(),
call_id.to_string(),
);
let turn_environment = selected_executor(&environments, &step_context.environments)?;
let parsed =
@@ -87,8 +87,12 @@ impl WriteStdinHandler {
));
};
let args = WriteStdinArgs::parse(&payload)?;
let context =
UnifiedExecContext::new(session.clone(), step_context, cancellation_token, call_id);
let context = UnifiedExecContext::new(
session.clone(),
step_context,
cancellation_token,
call_id.into(),
);
let response = session
.services
.unified_exec_manager
@@ -38,7 +38,7 @@ async fn invocation_for_payload(
turn,
cancellation_token: tokio_util::sync::CancellationToken::new(),
tracker: Arc::new(Mutex::new(TurnDiffTracker::new())),
call_id: call_id.to_string(),
call_id: call_id.into(),
tool_name: codex_tools::ToolName::plain(tool_name),
source: ToolCallSource::Direct,
payload,
@@ -351,7 +351,7 @@ async fn exec_command_rejects_login_when_selected_environment_disallows_it() {
turn,
cancellation_token: tokio_util::sync::CancellationToken::new(),
tracker: Arc::new(Mutex::new(TurnDiffTracker::new())),
call_id: "login-disallowed".to_string(),
call_id: "login-disallowed".into(),
tool_name: codex_tools::ToolName::plain("exec_command"),
source: ToolCallSource::Direct,
native_call: None,
@@ -442,7 +442,7 @@ async fn exec_command_reuses_foreign_windows_grant() {
turn,
cancellation_token: tokio_util::sync::CancellationToken::new(),
tracker: Arc::new(Mutex::new(TurnDiffTracker::new())),
call_id: "foreign-windows-grant".to_string(),
call_id: "foreign-windows-grant".into(),
tool_name: codex_tools::ToolName::plain("exec_command"),
source: ToolCallSource::Direct,
native_call: None,
@@ -484,7 +484,7 @@ async fn exec_command_pre_tool_use_payload_uses_raw_command() {
turn,
cancellation_token: tokio_util::sync::CancellationToken::new(),
tracker: Arc::new(Mutex::new(TurnDiffTracker::new())),
call_id: "call-43".to_string(),
call_id: "call-43".into(),
tool_name: codex_tools::ToolName::plain("exec_command"),
source: crate::tools::context::ToolCallSource::Direct,
payload,
@@ -515,7 +515,7 @@ async fn exec_command_pre_tool_use_cwd_resolves_selected_environment() {
turn,
cancellation_token: tokio_util::sync::CancellationToken::new(),
tracker: Arc::new(Mutex::new(TurnDiffTracker::new())),
call_id: "hook-cwd".to_string(),
call_id: "hook-cwd".into(),
tool_name: codex_tools::ToolName::plain("exec_command"),
source: ToolCallSource::Direct,
payload: ToolPayload::Function {
@@ -588,7 +588,7 @@ async fn exec_command_pre_tool_use_payload_skips_write_stdin() {
turn,
cancellation_token: tokio_util::sync::CancellationToken::new(),
tracker: Arc::new(Mutex::new(TurnDiffTracker::new())),
call_id: "call-44".to_string(),
call_id: "call-44".into(),
tool_name: codex_tools::ToolName::plain("write_stdin"),
source: crate::tools::context::ToolCallSource::Direct,
payload,
@@ -831,7 +831,7 @@ async fn exec_command_telemetry_records_configured_snapshot_mode(
turn,
cancellation_token: tokio_util::sync::CancellationToken::new(),
tracker: Arc::new(Mutex::new(TurnDiffTracker::new())),
call_id: "snapshot-metric".to_string(),
call_id: "snapshot-metric".into(),
tool_name: codex_tools::ToolName::plain("exec_command"),
source: ToolCallSource::Direct,
// Non-login commands cannot use V2 but must stay in the configured cohort.
@@ -212,7 +212,7 @@ impl ViewImageHandler {
}
let item = TurnItem::ImageView(ImageViewItem {
id: call_id,
id: call_id.into(),
path: path_uri,
});
session.emit_turn_item_started(turn.as_ref(), &item).await;
@@ -413,7 +413,7 @@ mod tests {
turn,
cancellation_token: tokio_util::sync::CancellationToken::new(),
tracker: Arc::new(Mutex::new(TurnDiffTracker::new())),
call_id: "call-view-image".to_string(),
call_id: "call-view-image".into(),
tool_name: codex_tools::ToolName::plain("view_image"),
source: ToolCallSource::Direct,
native_call: None,
@@ -445,7 +445,7 @@ mod tests {
turn,
cancellation_token: tokio_util::sync::CancellationToken::new(),
tracker: Arc::new(Mutex::new(TurnDiffTracker::new())),
call_id: "call-view-image".to_string(),
call_id: "call-view-image".into(),
tool_name: codex_tools::ToolName::plain("view_image"),
source: ToolCallSource::Direct,
native_call: None,
@@ -490,7 +490,7 @@ mod tests {
turn,
cancellation_token: tokio_util::sync::CancellationToken::new(),
tracker: Arc::new(Mutex::new(TurnDiffTracker::new())),
call_id: "call-view-image".to_string(),
call_id: "call-view-image".into(),
tool_name: codex_tools::ToolName::plain("view_image"),
source: ToolCallSource::Direct,
native_call: None,
@@ -530,7 +530,7 @@ mod tests {
turn,
cancellation_token: tokio_util::sync::CancellationToken::new(),
tracker: Arc::new(Mutex::new(TurnDiffTracker::new())),
call_id: "call-view-image".to_string(),
call_id: "call-view-image".into(),
tool_name: codex_tools::ToolName::plain("view_image"),
source: ToolCallSource::CodeMode {
cell_id: "cell-1".to_string(),
@@ -29,7 +29,7 @@ pub(crate) async fn review(invocation: &ToolInvocation) -> Result<(), FunctionCa
name: invocation.tool_name.name.clone(),
namespace: invocation.tool_name.namespace.clone(),
arguments: arguments.clone(),
call_id: invocation.call_id.clone(),
call_id: invocation.call_id.to_string(),
encrypted_content: None,
status: None,
encrypted_function_args: matches!(
@@ -61,7 +61,7 @@ pub(crate) async fn review(invocation: &ToolInvocation) -> Result<(), FunctionCa
context,
new_guardian_review_id(),
GuardianApprovalRequest::NativeToolCall {
id: invocation.call_id.clone(),
id: invocation.call_id.to_string(),
call: Box::new(item),
},
ApprovalRequestReasons::default(),
+13 -11
View File
@@ -39,13 +39,14 @@ use codex_extension_api::ToolCallOutcome;
use codex_history::ResponseItemEnvelope;
use codex_protocol::error::CodexErr;
use codex_protocol::models::ResponseInputItem;
use codex_tool_call_id::ToolCallId;
struct ToolCallTimingGuard {
started_at: Option<Instant>,
call_state: Arc<ToolCallState>,
conversation_id: String,
turn_id: String,
call_id: String,
call_id: ToolCallId,
tool_name: codex_tools::ToolName,
extensions: Arc<codex_extension_api::ExtensionRegistry<crate::config::Config>>,
}
@@ -496,15 +497,16 @@ impl ToolCallRuntime {
fn failure_response(call: ToolCall, err: FunctionCallError) -> ResponseInputItem {
let message = err.to_string();
let call_id = call.call_id.into();
match call.payload {
ToolPayload::ToolSearch { .. } => ResponseInputItem::ToolSearchOutput {
call_id: call.call_id,
call_id,
status: "completed".to_string(),
execution: "client".to_string(),
tools: Vec::new(),
},
ToolPayload::Custom { .. } => ResponseInputItem::CustomToolCallOutput {
call_id: call.call_id,
call_id,
name: None,
output: codex_protocol::models::FunctionCallOutputPayload {
body: codex_protocol::models::FunctionCallOutputBody::Text(message),
@@ -512,7 +514,7 @@ impl ToolCallRuntime {
},
},
_ => ResponseInputItem::FunctionCallOutput {
call_id: call.call_id,
call_id,
output: codex_protocol::models::FunctionCallOutputPayload {
body: codex_protocol::models::FunctionCallOutputBody::Text(message),
success: Some(false),
@@ -734,7 +736,7 @@ mod tests {
tracing::subscriber::with_default(subscriber, || {
let call = ToolCall {
tool_name: codex_tools::ToolName::plain("test_tool"),
call_id: "call-1".to_string(),
call_id: "call-1".into(),
payload: ToolPayload::Function {
arguments: "{}".to_string(),
},
@@ -789,7 +791,7 @@ mod tests {
tracing::subscriber::with_default(tracing::subscriber::NoSubscriber::default(), || {
let call = ToolCall {
tool_name: codex_tools::ToolName::plain("exec"),
call_id: "call-1".to_string(),
call_id: "call-1".into(),
payload: ToolPayload::Custom {
input: "text('ready')".to_string(),
},
@@ -912,7 +914,7 @@ mod tests {
let cancellation_token = CancellationToken::new();
let call = ToolCall {
tool_name,
call_id: "call-1".to_string(),
call_id: "call-1".into(),
payload: ToolPayload::Function {
arguments: "{}".to_string(),
},
@@ -1118,7 +1120,7 @@ mod tests {
let cancellation_token = CancellationToken::new();
let call = ToolCall {
tool_name,
call_id: "call-1".to_string(),
call_id: "call-1".into(),
payload: ToolPayload::Function {
arguments: "{}".to_string(),
},
@@ -1128,11 +1130,11 @@ mod tests {
let queued_call = ToolCall {
tool_name: queued_name,
call_id: "call-2".to_string(),
call_id: "call-2".into(),
..call.clone()
};
let held_call = ToolCall {
call_id: "held-at-start".to_string(),
call_id: "held-at-start".into(),
..call.clone()
};
let response = runtime
@@ -1150,7 +1152,7 @@ mod tests {
let gate = Arc::clone(&queued_runtime.parallel_execution);
assert!(gate.try_read().is_ok());
let expected_abort = ResponseInputItem::FunctionCallOutput {
call_id: queued_call.call_id.clone(),
call_id: queued_call.call_id.to_string(),
output: FunctionCallOutputPayload {
body: FunctionCallOutputBody::Text("aborted before dispatch".to_string()),
success: None,
+3 -2
View File
@@ -44,6 +44,7 @@ use codex_protocol::protocol::EventMsg;
use codex_rollout::state_db;
use codex_rollout_trace::ExecutionStatus;
use codex_shell_command::parse_command::parse_shell_script;
use codex_tool_call_id::ToolCallId;
use codex_tools::FunctionsNamespaceFunctionPrefixes;
use codex_tools::ToolName;
use codex_tools::ToolSearchInfo;
@@ -325,7 +326,7 @@ pub(crate) trait ToolArgumentDiffConsumer: Send {
}
pub(crate) struct AnyToolResult {
pub(crate) call_id: String,
pub(crate) call_id: ToolCallId,
pub(crate) payload: ToolPayload,
pub(crate) result: Box<dyn ToolOutput>,
pub(crate) post_tool_use_payload: Option<PostToolUsePayload>,
@@ -1239,7 +1240,7 @@ pub(crate) async fn apply_pre_tool_use(
let outcome = run_pre_tool_use_hooks(
&invocation.session,
&invocation.step_context,
invocation.call_id.clone(),
invocation.call_id.to_string(),
&payload.tool_name,
&payload.tool_input,
cwd,
+4 -4
View File
@@ -613,7 +613,7 @@ fn post_tool_use_feedback_output_preserves_fallback_token_limit_override(
expected_token_limit: usize,
) {
let result = AnyToolResult {
call_id: "call-1".to_string(),
call_id: "call-1".into(),
payload: ToolPayload::Function {
arguments: "{}".to_string(),
},
@@ -698,7 +698,7 @@ fn mcp_audio_producer_limit_is_transient_until_history_admission(file_backed_too
#[test]
fn post_tool_use_feedback_output_keeps_code_mode_result_typed() {
let result = AnyToolResult {
call_id: "call-1".to_string(),
call_id: "call-1".into(),
payload: ToolPayload::Function {
arguments: "{}".to_string(),
},
@@ -728,7 +728,7 @@ fn post_tool_use_feedback_output_keeps_code_mode_result_typed() {
);
let result = AnyToolResult {
call_id: "call-1".to_string(),
call_id: "call-1".into(),
payload: ToolPayload::Function {
arguments: "{}".to_string(),
},
@@ -922,7 +922,7 @@ fn test_invocation(
tracker: Arc::new(tokio::sync::Mutex::new(
crate::turn_diff_tracker::TurnDiffTracker::new(),
)),
call_id: call_id.to_string(),
call_id: call_id.into(),
tool_name,
source: crate::tools::context::ToolCallSource::Direct,
native_call: None,
+17 -9
View File
@@ -26,6 +26,7 @@ use codex_protocol::models::SearchToolCallParams;
#[cfg(test)]
use codex_protocol::openai_models::ModelInfo;
use codex_protocol::openai_models::ToolMode;
use codex_tool_call_id::ToolCallId;
use codex_tools::DiscoverableTool;
use codex_tools::ResponsesApiNamespaceTool;
use codex_tools::ToolName;
@@ -48,7 +49,7 @@ const EXPOSURE_HIDDEN: &str = "hidden";
#[derive(Clone, PartialEq)]
pub struct ToolCall {
pub tool_name: ToolName,
pub call_id: String,
pub call_id: ToolCallId,
pub payload: ToolPayload,
pub encrypted_function_args: Option<Vec<String>>,
/// Original function call, retained only for tools that opt into native review.
@@ -290,7 +291,7 @@ impl ToolRouter {
ref name,
ref namespace,
ref mut arguments,
ref call_id,
ref mut call_id,
ref mut encrypted_function_args,
..
} => {
@@ -300,15 +301,22 @@ impl ToolRouter {
.registry
.registered_tool(&tool_name)
.is_some_and(|tool| tool.native_review == NativeReview::Required);
let (arguments, encrypted_function_args) = if retain_native_call {
(arguments.clone(), encrypted_function_args.clone())
let (arguments, encrypted_function_args, call_id) = if retain_native_call {
(
arguments.clone(),
encrypted_function_args.clone(),
call_id.clone(),
)
} else {
(std::mem::take(arguments), encrypted_function_args.take())
(
std::mem::take(arguments),
encrypted_function_args.take(),
std::mem::take(call_id),
)
};
let call_id = call_id.clone();
Ok(Some(ToolCall {
tool_name,
call_id,
call_id: call_id.into(),
payload: ToolPayload::Function { arguments },
encrypted_function_args,
native_call: retain_native_call.then(|| Arc::new(item)),
@@ -328,7 +336,7 @@ impl ToolRouter {
})?;
Ok(Some(ToolCall {
tool_name: ToolName::plain("tool_search"),
call_id,
call_id: call_id.into(),
payload: ToolPayload::ToolSearch { arguments },
encrypted_function_args: None,
native_call: None,
@@ -343,7 +351,7 @@ impl ToolRouter {
..
} => Ok(Some(ToolCall {
tool_name: ToolName::new(namespace, name).with_default_namespace(),
call_id,
call_id: call_id.into(),
payload: ToolPayload::Custom { input },
encrypted_function_args: None,
native_call: None,
+9 -9
View File
@@ -231,7 +231,7 @@ async fn parallel_support_does_not_match_namespaced_local_tool_names() -> anyhow
.find(|name| {
router.tool_supports_parallel(&ToolCall {
tool_name: ToolName::plain(*name),
call_id: "call-parallel-tool".to_string(),
call_id: "call-parallel-tool".into(),
payload: ToolPayload::Function {
arguments: "{}".to_string(),
},
@@ -250,7 +250,7 @@ async fn parallel_support_does_not_match_namespaced_local_tool_names() -> anyhow
assert!(!router.tool_supports_parallel(&ToolCall {
tool_name: ToolName::namespaced("mcp__server__", parallel_tool_name),
call_id: "call-namespaced-tool".to_string(),
call_id: "call-namespaced-tool".into(),
payload: ToolPayload::Function {
arguments: "{}".to_string(),
},
@@ -287,7 +287,7 @@ async fn build_tool_call_uses_namespace_for_registry_name() -> anyhow::Result<()
call.tool_name,
ToolName::namespaced("mcp__codex_apps__calendar", tool_name)
);
assert_eq!(call.call_id, "call-namespace");
assert_eq!(call.call_id.as_str(), "call-namespace");
assert_eq!(call.encrypted_function_args, Some(Vec::new()));
assert_eq!(call.direct_source(), ToolCallSource::Direct);
match call.payload {
@@ -325,7 +325,7 @@ async fn build_custom_tool_call_uses_namespace_for_registry_name() -> anyhow::Re
call,
ToolCall {
tool_name: ToolName::namespaced("mcp__python", tool_name),
call_id: "call-namespace".to_string(),
call_id: "call-namespace".into(),
payload: ToolPayload::Custom {
input: "print('hello')".to_string(),
},
@@ -432,7 +432,7 @@ async fn mcp_parallel_support_uses_handler_data() -> anyhow::Result<()> {
let call = ToolCall {
tool_name: ToolName::namespaced("mcp__echo__", "query_with_delay"),
call_id: "call-handler".to_string(),
call_id: "call-handler".into(),
payload: ToolPayload::Function {
arguments: "{}".to_string(),
},
@@ -449,7 +449,7 @@ async fn mcp_parallel_support_uses_handler_data() -> anyhow::Result<()> {
let different_server_call = ToolCall {
tool_name: ToolName::namespaced("mcp__hello_echo__", "query_with_delay"),
call_id: "call-other-server".to_string(),
call_id: "call-other-server".into(),
payload: ToolPayload::Function {
arguments: "{}".to_string(),
},
@@ -466,7 +466,7 @@ async fn mcp_parallel_support_uses_handler_data() -> anyhow::Result<()> {
let hidden_call = ToolCall {
tool_name: ToolName::namespaced("mcp__hidden_echo__", "query_with_delay"),
call_id: "call-hidden".to_string(),
call_id: "call-hidden".into(),
payload: ToolPayload::Function {
arguments: "{}".to_string(),
},
@@ -478,7 +478,7 @@ async fn mcp_parallel_support_uses_handler_data() -> anyhow::Result<()> {
let nested_only_call = ToolCall {
tool_name: ToolName::namespaced("mcp__nested_echo__", "query_with_delay"),
call_id: "call-nested-only-server".to_string(),
call_id: "call-nested-only-server".into(),
payload: ToolPayload::Function {
arguments: "{}".to_string(),
},
@@ -504,7 +504,7 @@ async fn tools_without_handlers_do_not_support_parallel() -> anyhow::Result<()>
assert!(!router.tool_supports_parallel(&ToolCall {
tool_name: ToolName::plain("web_search"),
call_id: "call-web-search".to_string(),
call_id: "call-web-search".into(),
payload: ToolPayload::Function {
arguments: "{}".to_string(),
},
@@ -16,6 +16,7 @@ use codex_rollout_trace::ToolDispatchPayload;
use codex_rollout_trace::ToolDispatchRequester;
use codex_rollout_trace::ToolDispatchResult;
use codex_rollout_trace::ToolDispatchTraceContext;
use codex_tool_call_id::ToolCallId;
/// Keeps registry results and abandoned dispatches paired with trace end events.
pub(crate) struct ToolDispatchTrace {
@@ -62,7 +63,7 @@ fn tool_dispatch_invocation(invocation: &ToolInvocation) -> Option<ToolDispatchI
let requester = match &invocation.source {
ToolCallSource::Direct | ToolCallSource::DirectPlaintextMessage => {
ToolDispatchRequester::Model {
model_visible_call_id: invocation.call_id.clone(),
model_visible_call_id: invocation.call_id.to_string(),
}
}
ToolCallSource::CodeMode {
@@ -92,7 +93,7 @@ fn tool_dispatch_invocation(invocation: &ToolInvocation) -> Option<ToolDispatchI
fn tool_dispatch_result(
invocation: &ToolInvocation,
call_id: &str,
call_id: &ToolCallId,
payload: &ToolPayload,
result: &dyn ToolOutput,
) -> Option<ToolDispatchResult> {
@@ -395,7 +395,7 @@ fn test_invocation_with_payload(
turn,
cancellation_token: CancellationToken::new(),
tracker: Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::new())),
call_id: call_id.to_string(),
call_id: call_id.into(),
tool_name,
source,
payload,
@@ -55,7 +55,7 @@ fn capture_keeps_the_first_confirmed_rewritten_message(budgeting: ContextBudgeti
fn messaging_result(name: &str, input: Value, success: bool) -> AnyToolResult {
AnyToolResult {
call_id: "message-call".to_owned(),
call_id: "message-call".into(),
payload: ToolPayload::Function {
arguments: r#"{"text":"Original question before hooks"}"#.to_owned(),
},
+1
View File
@@ -16,6 +16,7 @@ workspace = true
anyhow = { workspace = true }
codex-code-mode = { workspace = true }
codex-protocol = { workspace = true }
codex-tool-call-id = { workspace = true }
http = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true, features = ["raw_value"] }
+3 -2
View File
@@ -15,6 +15,7 @@ use crate::model::AgentThreadId;
use crate::model::CodeCellRuntimeStatus;
use crate::model::CodexTurnId;
use crate::model::ModelVisibleCallId;
use crate::model::ToolCallId;
use crate::payload::RawPayloadKind;
use crate::raw_event::RawTraceEventContext;
use crate::raw_event::RawTraceEventPayload;
@@ -123,14 +124,14 @@ impl CodeCellTraceContext {
/// Records a host-confirmed wait target before the handler returns. A missing cell
/// or rejected argument has no such observation. This does not imply caller delivery.
pub fn record_wait_target(&self, tool_call_id: &str) {
pub fn record_wait_target(&self, tool_call_id: &ToolCallId) {
let CodeCellTraceContextState::Enabled(context) = &self.state else {
return;
};
if let Err(err) = context.writer.enqueue_event(
RawTraceEventContext::turn(&context.thread_id, &context.codex_turn_id),
RawTraceEventPayload::CodeCellWaitTargetResolved {
tool_call_id: tool_call_id.to_owned(),
tool_call_id: tool_call_id.clone(),
runtime_cell_id: context.runtime_cell_id.clone(),
},
) {
+3 -3
View File
@@ -1,7 +1,8 @@
//! Reduced rollout trace model.
//!
//! These types describe the deterministic replay output. They intentionally
//! separate model-visible conversation from runtime/debug objects.
//! separate model-visible conversation from runtime/debug objects. [`ToolCallId`]
//! identifies a runtime tool invocation, including nested calls made by Code Mode.
use std::collections::BTreeMap;
@@ -14,6 +15,7 @@ mod conversation;
mod runtime;
mod session;
pub use codex_tool_call_id::ToolCallId;
pub use conversation::*;
pub use runtime::*;
pub use session::*;
@@ -30,8 +32,6 @@ pub type ConversationItemId = String;
pub type InferenceCallId = String;
/// Globally unique ID for one concrete MCP backend request.
pub type McpCallId = String;
/// Reducer-owned ID for one runtime tool-call object.
pub type ToolCallId = String;
/// Responses `call_id` / custom-tool call ID visible in inference payloads.
pub type ModelVisibleCallId = String;
/// Tool invocation ID assigned inside the code-mode JavaScript runtime.
@@ -477,7 +477,9 @@ impl TraceReducer {
// ownership can be proven.
return Ok(());
};
push_unique(&mut cell.nested_tool_call_ids, tool_call_id);
if !cell.nested_tool_call_ids.contains(tool_call_id) {
cell.nested_tool_call_ids.push(tool_call_id.clone());
}
Ok(())
}
@@ -87,7 +87,7 @@ fn code_cell_lifecycle_links_nested_tools_and_outputs_without_inferring_legacy_w
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "nested-tool-1".to_string(),
tool_call_id: "nested-tool-1".into(),
model_visible_call_id: None,
code_mode_runtime_tool_id: Some("tool-1".to_string()),
requester: RawToolCallRequester::CodeCell {
@@ -105,7 +105,7 @@ fn code_cell_lifecycle_links_nested_tools_and_outputs_without_inferring_legacy_w
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallEnded {
tool_call_id: "nested-tool-1".to_string(),
tool_call_id: "nested-tool-1".into(),
status: ExecutionStatus::Completed,
result_payload: None,
},
@@ -138,7 +138,7 @@ fn code_cell_lifecycle_links_nested_tools_and_outputs_without_inferring_legacy_w
writer.append_with_context(
trace_context("turn-2"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "wait-tool-1".to_string(),
tool_call_id: "wait-tool-1".into(),
model_visible_call_id: Some("wait-call".to_string()),
code_mode_runtime_tool_id: None,
requester: RawToolCallRequester::Model,
@@ -186,7 +186,10 @@ fn code_cell_lifecycle_links_nested_tools_and_outputs_without_inferring_legacy_w
assert_eq!(cell.runtime_status, CodeCellRuntimeStatus::Completed);
assert_eq!(cell.execution.status, ExecutionStatus::Completed);
assert_eq!(cell.runtime_cell_id, Some("1".to_string()));
assert_eq!(cell.nested_tool_call_ids, vec!["nested-tool-1"]);
assert_eq!(
cell.nested_tool_call_ids,
vec![crate::ToolCallId::from("nested-tool-1")]
);
// The legacy request alone does not establish that the host resolved a target.
assert!(cell.wait_tool_call_ids.is_empty());
assert_eq!(cell.output_item_ids, vec![output_item_id.clone()]);
@@ -489,7 +492,7 @@ fn runtime_code_cell_ids_can_repeat_across_threads_and_after_resume() -> anyhow:
pending_dispatches.push(dispatch);
if wait_id == "confirmed" {
crate::CodeCellTraceContext::enabled(Arc::clone(&writer), thread_id, turn_id, "1")
.record_wait_target(wait_id);
.record_wait_target(&wait_id.into());
}
}
let response = writer.write_json_payload(
@@ -513,7 +516,7 @@ fn runtime_code_cell_ids_can_repeat_across_threads_and_after_resume() -> anyhow:
if turn_id == "turn-resumed" {
// The pre-resume wait is confirmed after the new cell has reused its handle.
crate::CodeCellTraceContext::enabled(Arc::clone(&writer), thread_id, "turn-child", "1")
.record_wait_target("late");
.record_wait_target(&"late".into());
}
writer.append_with_context(
trace_context_for_thread(thread_id, turn_id),
@@ -550,7 +553,7 @@ fn runtime_code_cell_ids_can_repeat_across_threads_and_after_resume() -> anyhow:
);
assert_eq!(
rollout.code_cells[&child_cell_id].wait_tool_call_ids,
["confirmed"]
[crate::ToolCallId::from("confirmed")]
);
assert!(
rollout.code_cells[&root_cell_id]
@@ -1495,7 +1495,7 @@ fn late_tool_start_with_image_limit(body_limit: usize) -> anyhow::Result<()> {
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "tool-1".to_string(),
tool_call_id: "tool-1".into(),
model_visible_call_id: Some("call-1".to_string()),
code_mode_runtime_tool_id: None,
requester: crate::raw_event::RawToolCallRequester::Model,
@@ -1516,7 +1516,7 @@ fn late_tool_start_with_image_limit(body_limit: usize) -> anyhow::Result<()> {
trace_context("turn-1"),
RawTraceEventPayload::ToolCallRuntimeStarted {
kind: ToolCallKind::ExecCommand,
tool_call_id: "tool-1".to_string(),
tool_call_id: "tool-1".into(),
runtime_payload: runtime,
},
)?;
@@ -1524,7 +1524,7 @@ fn late_tool_start_with_image_limit(body_limit: usize) -> anyhow::Result<()> {
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallEnded {
tool_call_id: "tool-1".to_string(),
tool_call_id: "tool-1".into(),
status: ExecutionStatus::Completed,
result_payload: None,
},
@@ -1558,7 +1558,7 @@ fn late_tool_start_with_image_limit(body_limit: usize) -> anyhow::Result<()> {
assert_eq!(
first_inference.tool_call_ids_started_by_response,
vec!["tool-1".to_string()],
vec![crate::ToolCallId::from("tool-1")],
);
assert_eq!(
tool_call.model_visible_call_item_ids,
@@ -1573,7 +1573,7 @@ fn late_tool_start_with_image_limit(body_limit: usize) -> anyhow::Result<()> {
assert_eq!(
rollout.conversation_items[output_item_id].produced_by,
vec![ProducerRef::Tool {
tool_call_id: "tool-1".to_string(),
tool_call_id: "tool-1".into(),
}],
);
}
+2 -1
View File
@@ -18,6 +18,7 @@ use crate::bundle::TRACE_MANIFEST_SCHEMA_VERSION;
use crate::bundle::TraceBundleManifest;
use crate::model::ExecutionStatus;
use crate::model::RolloutTrace;
use crate::model::ToolCallId;
use crate::shard::PayloadReader;
use crate::raw_event::RAW_TRACE_EVENT_SCHEMA_VERSION;
@@ -263,7 +264,7 @@ struct TraceReducer {
/// Legacy collaboration events and automatic agent results lack a source-to-item ID.
pending_agent_interaction_edges: Vec<PendingAgentInteractionEdge>,
/// V2 tool activity and the recipient's history item can arrive in either order.
native_tool_deliveries: BTreeMap<String, tool::NativeToolDelivery>,
native_tool_deliveries: BTreeMap<ToolCallId, tool::NativeToolDelivery>,
}
impl TraceReducer {
+8 -8
View File
@@ -414,13 +414,13 @@ impl TraceReducer {
fn ensure_unique_model_visible_tool_call(
&self,
model_visible_call_id: Option<&str>,
tool_call_id: &str,
tool_call_id: &ToolCallId,
) -> Result<()> {
let Some(model_visible_call_id) = model_visible_call_id else {
return Ok(());
};
if let Some(existing) = self.single_tool_for_model_visible_call(model_visible_call_id)?
&& existing != tool_call_id
&& existing != *tool_call_id
{
bail!("duplicate tool call for model-visible call id {model_visible_call_id}");
}
@@ -460,7 +460,7 @@ impl TraceReducer {
.collect::<Vec<_>>()
}
fn add_tool_call_item(&mut self, tool_call_id: &str, item_id: &str) -> Result<()> {
fn add_tool_call_item(&mut self, tool_call_id: &ToolCallId, item_id: &str) -> Result<()> {
let Some(tool_call) = self.rollout.tool_calls.get_mut(tool_call_id) else {
bail!("tool call {tool_call_id} disappeared during conversation linking");
};
@@ -468,7 +468,7 @@ impl TraceReducer {
Ok(())
}
fn add_tool_output_item(&mut self, tool_call_id: &str, item_id: &str) -> Result<()> {
fn add_tool_output_item(&mut self, tool_call_id: &ToolCallId, item_id: &str) -> Result<()> {
let Some(tool_call) = self.rollout.tool_calls.get_mut(tool_call_id) else {
bail!("tool call {tool_call_id} disappeared during output linking");
};
@@ -478,7 +478,7 @@ impl TraceReducer {
bail!("conversation item {item_id} disappeared during output linking");
};
let producer = ProducerRef::Tool {
tool_call_id: tool_call_id.to_string(),
tool_call_id: tool_call_id.clone(),
};
if !item.produced_by.contains(&producer) {
item.produced_by.push(producer);
@@ -486,7 +486,7 @@ impl TraceReducer {
Ok(())
}
fn link_tool_to_inference_response(&mut self, tool_call_id: &str) {
fn link_tool_to_inference_response(&mut self, tool_call_id: &ToolCallId) {
let Some(tool_call) = self.rollout.tool_calls.get(tool_call_id) else {
return;
};
@@ -501,11 +501,11 @@ impl TraceReducer {
.any(|item_id| call_item_ids.contains(item_id))
&& !inference
.tool_call_ids_started_by_response
.contains(&tool_call_id.to_string())
.contains(tool_call_id)
{
inference
.tool_call_ids_started_by_response
.push(tool_call_id.to_string());
.push(tool_call_id.clone());
}
}
}
@@ -19,6 +19,7 @@ use crate::model::ConversationRole;
use crate::model::InteractionEdge;
use crate::model::InteractionEdgeKind;
use crate::model::ProducerRef;
use crate::model::ToolCallId;
use crate::model::ToolCallKind;
use crate::model::TraceAnchor;
use crate::payload::RawPayloadRef;
@@ -69,7 +70,7 @@ 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,
tool_call_id: &ToolCallId,
runtime_payload: &RawPayloadRef,
) -> Result<()> {
if !runtime_payload.is_complete() {
@@ -130,7 +131,7 @@ impl TraceReducer {
pub(super) fn end_agent_interaction_from_runtime(
&mut self,
wall_time_unix_ms: i64,
tool_call_id: &str,
tool_call_id: &ToolCallId,
runtime_payload: &RawPayloadRef,
) -> Result<()> {
let kind = self.rollout.tool_calls[tool_call_id].kind.clone();
@@ -191,7 +192,7 @@ impl TraceReducer {
fn end_sub_agent_activity(
&mut self,
wall_time_unix_ms: i64,
tool_call_id: &str,
tool_call_id: &ToolCallId,
tool_kind: &ToolCallKind,
payload: &SubAgentActivityEvent,
) -> Result<()> {
@@ -202,7 +203,7 @@ impl TraceReducer {
ToolCallKind::AssignAgentTask | ToolCallKind::SendMessage,
SubAgentActivityKind::Interacted,
) => {
self.native_tool_delivery(tool_call_id.to_owned(), target_thread_id)?
self.native_tool_delivery(tool_call_id.clone(), target_thread_id)?
.activity_at_unix_ms = Some(wall_time_unix_ms);
Ok(())
}
@@ -222,7 +223,7 @@ impl TraceReducer {
fn native_tool_delivery(
&mut self,
call_id: String,
call_id: ToolCallId,
receiver: String,
) -> Result<&mut NativeToolDelivery> {
match self.native_tool_deliveries.entry(call_id) {
@@ -240,7 +241,7 @@ impl TraceReducer {
pub(in crate::reducer) fn record_agent_message_target(
&mut self,
call_id: String,
call_id: ToolCallId,
receiver: String,
item_id: String,
) -> Result<()> {
@@ -348,7 +349,7 @@ impl TraceReducer {
/// 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,
tool_call_id: &ToolCallId,
result_payload: Option<&RawPayloadRef>,
) -> Result<()> {
let Some(result_payload) = result_payload else {
@@ -387,7 +388,7 @@ impl TraceReducer {
fn end_spawn_agent_interaction(
&mut self,
wall_time_unix_ms: i64,
tool_call_id: &str,
tool_call_id: &ToolCallId,
payload: &CollabAgentSpawnEndEvent,
) -> Result<()> {
let Some(child_thread_id) = payload.new_thread_id else {
@@ -402,7 +403,7 @@ impl TraceReducer {
edge_id,
kind: InteractionEdgeKind::SpawnAgent,
source: TraceAnchor::ToolCall {
tool_call_id: tool_call_id.to_string(),
tool_call_id: tool_call_id.clone(),
},
target_thread_id: child_thread_id.clone(),
message_author,
@@ -417,7 +418,7 @@ impl TraceReducer {
fn end_message_agent_interaction(
&mut self,
wall_time_unix_ms: i64,
tool_call_id: &str,
tool_call_id: &ToolCallId,
edge_kind: InteractionEdgeKind,
payload: &CollabAgentInteractionEndEvent,
) -> Result<()> {
@@ -432,7 +433,7 @@ impl TraceReducer {
fn queue_message_agent_interaction(
&mut self,
tool_call_id: &str,
tool_call_id: &ToolCallId,
kind: InteractionEdgeKind,
target_thread_id: String,
message_content: String,
@@ -444,7 +445,7 @@ impl TraceReducer {
edge_id: tool_edge_id(tool_call_id),
kind,
source: TraceAnchor::ToolCall {
tool_call_id: tool_call_id.to_string(),
tool_call_id: tool_call_id.clone(),
},
target_thread_id,
message_author,
@@ -456,7 +457,7 @@ impl TraceReducer {
})
}
fn agent_tool_payload_ids(&self, tool_call_id: &str) -> Result<Vec<String>> {
fn agent_tool_payload_ids(&self, tool_call_id: &ToolCallId) -> 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}")
@@ -476,7 +477,7 @@ impl TraceReducer {
fn upsert_close_agent_interaction(
&mut self,
tool_call_id: &str,
tool_call_id: &ToolCallId,
target_thread_id: String,
ended_at_unix_ms: Option<i64>,
) -> Result<()> {
@@ -498,7 +499,7 @@ impl TraceReducer {
edge_id: tool_edge_id(tool_call_id),
kind: InteractionEdgeKind::CloseAgent,
source: TraceAnchor::ToolCall {
tool_call_id: tool_call_id.to_string(),
tool_call_id: tool_call_id.clone(),
},
target: TraceAnchor::Thread {
thread_id: target_thread_id,
@@ -803,11 +804,11 @@ fn extend_unique(items: &mut Vec<String>, new_items: Vec<String>) {
}
}
fn tool_edge_id(tool_call_id: &str) -> String {
fn tool_edge_id(tool_call_id: &ToolCallId) -> String {
format!("edge:tool:{tool_call_id}")
}
fn tool_call_source_matches(anchor: &TraceAnchor, tool_call_id: &str) -> bool {
fn tool_call_source_matches(anchor: &TraceAnchor, tool_call_id: &ToolCallId) -> bool {
matches!(anchor, TraceAnchor::ToolCall { tool_call_id: source } if source == tool_call_id)
}
@@ -119,7 +119,7 @@ fn spawn_runtime_payload_targets_delivered_child_message() -> anyhow::Result<()>
assert_eq!(
edge.source,
TraceAnchor::ToolCall {
tool_call_id: "call-spawn".to_string()
tool_call_id: "call-spawn".into()
}
);
let target_item_id = target_conversation_item_id(&edge.target);
@@ -164,7 +164,7 @@ fn spawn_runtime_payload_falls_back_to_child_thread_without_delivery_item() -> a
assert_eq!(
edge.source,
TraceAnchor::ToolCall {
tool_call_id: "call-spawn".to_string()
tool_call_id: "call-spawn".into()
}
);
assert_eq!(
@@ -208,7 +208,7 @@ fn sub_agent_started_activity_creates_spawn_edge() -> anyhow::Result<()> {
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "call-spawn-v2".to_string(),
tool_call_id: "call-spawn-v2".into(),
model_visible_call_id: Some("call-spawn-v2".to_string()),
code_mode_runtime_tool_id: None,
requester: RawToolCallRequester::Model,
@@ -234,7 +234,7 @@ fn sub_agent_started_activity_creates_spawn_edge() -> anyhow::Result<()> {
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: "call-spawn-v2".to_string(),
tool_call_id: "call-spawn-v2".into(),
status: ExecutionStatus::Completed,
runtime_payload: activity_payload.clone(),
},
@@ -388,7 +388,7 @@ fn send_message_runtime_payload_targets_delivered_child_message() -> anyhow::Res
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "call-send".to_string(),
tool_call_id: "call-send".into(),
model_visible_call_id: Some("call-send".to_string()),
code_mode_runtime_tool_id: None,
requester: RawToolCallRequester::Model,
@@ -415,7 +415,7 @@ fn send_message_runtime_payload_targets_delivered_child_message() -> anyhow::Res
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallRuntimeStarted {
kind: ToolCallKind::SendMessage,
tool_call_id: "call-send".to_string(),
tool_call_id: "call-send".into(),
runtime_payload: begin_payload,
},
)?;
@@ -432,7 +432,7 @@ fn send_message_runtime_payload_targets_delivered_child_message() -> anyhow::Res
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: "call-send".to_string(),
tool_call_id: "call-send".into(),
status: ExecutionStatus::Completed,
runtime_payload: end_payload,
},
@@ -462,7 +462,7 @@ fn send_message_runtime_payload_targets_delivered_child_message() -> anyhow::Res
assert_eq!(
edge.source,
TraceAnchor::ToolCall {
tool_call_id: "call-send".to_string()
tool_call_id: "call-send".into()
}
);
let target_item_id = target_conversation_item_id(&edge.target);
@@ -495,7 +495,7 @@ fn send_message_activity_targets_delivered_child_message() -> anyhow::Result<()>
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "call-send-v2".to_string(),
tool_call_id: "call-send-v2".into(),
model_visible_call_id: Some("call-send-v2".to_string()),
code_mode_runtime_tool_id: None,
requester: RawToolCallRequester::Model,
@@ -554,7 +554,7 @@ fn send_message_activity_targets_delivered_child_message() -> anyhow::Result<()>
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: "call-send-v2".to_string(),
tool_call_id: "call-send-v2".into(),
status: ExecutionStatus::Completed,
runtime_payload: activity_payload.clone(),
},
@@ -617,7 +617,7 @@ fn followup_activity_targets_delivered_child_message() -> anyhow::Result<()> {
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "call-followup-v2".to_string(),
tool_call_id: "call-followup-v2".into(),
model_visible_call_id: Some("call-followup-v2".to_string()),
code_mode_runtime_tool_id: None,
requester: RawToolCallRequester::Model,
@@ -643,7 +643,7 @@ fn followup_activity_targets_delivered_child_message() -> anyhow::Result<()> {
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: "call-followup-v2".to_string(),
tool_call_id: "call-followup-v2".into(),
status: ExecutionStatus::Completed,
runtime_payload: activity_payload.clone(),
},
@@ -727,7 +727,7 @@ fn close_agent_runtime_payload_targets_thread() -> anyhow::Result<()> {
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "call-close".to_string(),
tool_call_id: "call-close".into(),
model_visible_call_id: Some("call-close".to_string()),
code_mode_runtime_tool_id: None,
requester: RawToolCallRequester::Model,
@@ -752,7 +752,7 @@ fn close_agent_runtime_payload_targets_thread() -> anyhow::Result<()> {
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallRuntimeStarted {
kind: ToolCallKind::CloseAgent,
tool_call_id: "call-close".to_string(),
tool_call_id: "call-close".into(),
runtime_payload: begin_payload.clone(),
},
)?;
@@ -770,7 +770,7 @@ fn close_agent_runtime_payload_targets_thread() -> anyhow::Result<()> {
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: "call-close".to_string(),
tool_call_id: "call-close".into(),
status: ExecutionStatus::Completed,
runtime_payload: end_payload.clone(),
},
@@ -782,7 +782,7 @@ fn close_agent_runtime_payload_targets_thread() -> anyhow::Result<()> {
writer.append_with_context(
trace_context_for_agent("turn-1"),
RawTraceEventPayload::ToolCallEnded {
tool_call_id: "call-close".to_string(),
tool_call_id: "call-close".into(),
status: ExecutionStatus::Completed,
result_payload: Some(result_payload.clone()),
},
@@ -798,7 +798,7 @@ fn close_agent_runtime_payload_targets_thread() -> anyhow::Result<()> {
assert_eq!(
edge.source,
TraceAnchor::ToolCall {
tool_call_id: "call-close".to_string()
tool_call_id: "call-close".into()
}
);
assert_eq!(
@@ -1025,7 +1025,7 @@ fn append_spawn_agent_tool_lifecycle(
writer.append_with_context(
trace_context_for_agent(turn_id),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "call-spawn".to_string(),
tool_call_id: "call-spawn".into(),
model_visible_call_id: Some("call-spawn".to_string()),
code_mode_runtime_tool_id: None,
requester: RawToolCallRequester::Model,
@@ -1051,7 +1051,7 @@ fn append_spawn_agent_tool_lifecycle(
trace_context_for_agent(turn_id),
RawTraceEventPayload::ToolCallRuntimeStarted {
kind: ToolCallKind::SpawnAgent,
tool_call_id: "call-spawn".to_string(),
tool_call_id: "call-spawn".into(),
runtime_payload: begin.clone(),
},
)?;
@@ -1071,7 +1071,7 @@ fn append_spawn_agent_tool_lifecycle(
writer.append_with_context(
trace_context_for_agent(turn_id),
RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: "call-spawn".to_string(),
tool_call_id: "call-spawn".into(),
status: ExecutionStatus::Completed,
runtime_payload: end.clone(),
},
@@ -1084,7 +1084,7 @@ fn append_spawn_agent_tool_lifecycle(
writer.append_with_context(
trace_context_for_agent(turn_id),
RawTraceEventPayload::ToolCallEnded {
tool_call_id: "call-spawn".to_string(),
tool_call_id: "call-spawn".into(),
status: ExecutionStatus::Completed,
result_payload: Some(result.clone()),
},
@@ -60,7 +60,7 @@ fn mcp_calls_keep_callable_identity_and_classify_the_backend() -> anyhow::Result
ToolDispatchInvocation {
thread_id: ROOT_THREAD_ID.to_string(),
codex_turn_id: "turn-1".to_string(),
tool_call_id: "call-mcp".to_string(),
tool_call_id: "call-mcp".into(),
tool_name: tool_name.to_string(),
tool_namespace: Some(namespace.to_string()),
requester: ToolDispatchRequester::CodeCell {
@@ -96,7 +96,7 @@ fn mcp_calls_keep_callable_identity_and_classify_the_backend() -> anyhow::Result
)?;
writer.append(RawTraceEventPayload::ToolCallRuntimeStarted {
kind: expected.kind.clone(),
tool_call_id: "call-mcp".to_string(),
tool_call_id: "call-mcp".into(),
runtime_payload: begin.clone(),
})?;
expected.raw_runtime_payload_ids.push(begin.raw_payload_id);
@@ -107,7 +107,7 @@ fn mcp_calls_keep_callable_identity_and_classify_the_backend() -> anyhow::Result
// 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(),
tool_call_id: "call-mcp".into(),
mcp_call_id: "mcp-correlation-1".to_string(),
})?;
expected.mcp_call_id = Some("mcp-correlation-1".to_string());
@@ -120,7 +120,7 @@ fn mcp_calls_keep_callable_identity_and_classify_the_backend() -> anyhow::Result
}),
)?;
writer.append(RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: "call-mcp".to_string(),
tool_call_id: "call-mcp".into(),
status: crate::ExecutionStatus::Completed,
runtime_payload: end.clone(),
})?;
@@ -27,6 +27,7 @@ use crate::model::TerminalOperationKind;
use crate::model::TerminalRequest;
use crate::model::TerminalResult;
use crate::model::TerminalSession;
use crate::model::ToolCallId;
use crate::model::ToolCallKind;
use crate::payload::RawPayloadKind;
use crate::payload::RawPayloadRef;
@@ -43,7 +44,7 @@ impl TraceReducer {
seq: RawEventSeq,
wall_time_unix_ms: i64,
thread_id: &str,
tool_call_id: &str,
tool_call_id: &ToolCallId,
kind: &ToolCallKind,
invocation_payload: Option<&RawPayloadRef>,
) -> Result<Option<TerminalOperationId>> {
@@ -86,7 +87,7 @@ impl TraceReducer {
seq: RawEventSeq,
wall_time_unix_ms: i64,
thread_id: &str,
tool_call_id: &str,
tool_call_id: &ToolCallId,
kind: &ToolCallKind,
runtime_payload: &RawPayloadRef,
) -> Result<Option<TerminalOperationId>> {
@@ -132,7 +133,7 @@ impl TraceReducer {
TerminalOperation {
operation_id: operation_id.clone(),
terminal_id: None,
tool_call_id: start.tool_call_id.to_string(),
tool_call_id: start.tool_call_id.clone(),
kind: start.operation_kind,
execution: ExecutionWindow {
started_at_unix_ms: start.wall_time_unix_ms,
@@ -296,8 +297,8 @@ impl TraceReducer {
/// 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,
tool_call_id: &ToolCallId,
exec_tool_call_id: &ToolCallId,
) -> Result<()> {
let stdin = self
.rollout
@@ -358,7 +359,7 @@ impl TraceReducer {
/// 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,
tool_call_id: &ToolCallId,
) -> 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");
@@ -423,7 +424,7 @@ struct TerminalOperationStart<'a> {
seq: RawEventSeq,
wall_time_unix_ms: i64,
thread_id: &'a str,
tool_call_id: &'a str,
tool_call_id: &'a ToolCallId,
operation_kind: TerminalOperationKind,
raw_payload: &'a RawPayloadRef,
request: ParsedTerminalRequest,
@@ -80,7 +80,7 @@ fn check_exec_terminal_result(
let _tool_start = writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "tool-1".to_string(),
tool_call_id: "tool-1".into(),
model_visible_call_id: Some("call-1".to_string()),
code_mode_runtime_tool_id: None,
requester: crate::raw_event::RawToolCallRequester::Model,
@@ -104,7 +104,7 @@ fn check_exec_terminal_result(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallRuntimeStarted {
kind: ToolCallKind::ExecCommand,
tool_call_id: "tool-1".to_string(),
tool_call_id: "tool-1".into(),
runtime_payload: runtime_start_payload,
},
)?;
@@ -131,7 +131,7 @@ fn check_exec_terminal_result(
let runtime_end = writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: "tool-1".to_string(),
tool_call_id: "tool-1".into(),
status: ExecutionStatus::Completed,
runtime_payload: runtime_end_payload,
},
@@ -152,7 +152,7 @@ fn check_exec_terminal_result(
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallEnded {
tool_call_id: "tool-1".to_string(),
tool_call_id: "tool-1".into(),
status: ExecutionStatus::Completed,
result_payload: Some(result_payload),
},
@@ -199,7 +199,7 @@ fn check_exec_terminal_result(
TerminalOperation {
operation_id: operation_id.clone(),
terminal_id: Some("terminal_session:terminal_operation:1".to_string()),
tool_call_id: "tool-1".to_string(),
tool_call_id: "tool-1".into(),
kind: TerminalOperationKind::ExecCommand,
execution: ExecutionWindow {
started_at_unix_ms: runtime_start.wall_time_unix_ms,
@@ -295,13 +295,13 @@ fn reused_process_ids_keep_sessions_and_stdin_joins_distinct() -> anyhow::Result
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: "tool-0".to_string(),
tool_call_id: "tool-0".into(),
status: ExecutionStatus::Completed,
runtime_payload: response,
},
)?;
}
let tool_call_id = format!("tool-{index}");
let tool_call_id = crate::ToolCallId::from(format!("tool-{index}"));
writer.append_with_context(
trace_context_for_thread(thread, turn),
RawTraceEventPayload::ToolCallStarted {
@@ -369,7 +369,7 @@ fn reused_process_ids_keep_sessions_and_stdin_joins_distinct() -> anyhow::Result
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(),
tool_call_id: "tool-5".into(),
kind: TerminalOperationKind::WriteStdin,
execution: ExecutionWindow {
started_at_unix_ms: runtime_start.wall_time_unix_ms,
@@ -394,8 +394,8 @@ fn reused_process_ids_keep_sessions_and_stdin_joins_distinct() -> anyhow::Result
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(),
tool_call_id: "tool-2".into(),
exec_tool_call_id: "tool-4".into(),
},
)?;
let mut expected = rollout;
@@ -447,7 +447,7 @@ fn dispatch_write_stdin_payload_reduces_to_terminal_operation() -> anyhow::Resul
let tool_start = writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "tool-stdin".to_string(),
tool_call_id: "tool-stdin".into(),
model_visible_call_id: Some("call-stdin".to_string()),
code_mode_runtime_tool_id: None,
requester: crate::raw_event::RawToolCallRequester::Model,
@@ -472,7 +472,7 @@ fn dispatch_write_stdin_payload_reduces_to_terminal_operation() -> anyhow::Resul
let tool_end = writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallEnded {
tool_call_id: "tool-stdin".to_string(),
tool_call_id: "tool-stdin".into(),
status: ExecutionStatus::Completed,
result_payload: Some(response_payload),
},
@@ -496,7 +496,7 @@ fn dispatch_write_stdin_payload_reduces_to_terminal_operation() -> anyhow::Resul
TerminalOperation {
operation_id: operation_id.clone(),
terminal_id: Some("terminal_session:terminal_operation:1".to_string()),
tool_call_id: "tool-stdin".to_string(),
tool_call_id: "tool-stdin".into(),
kind: TerminalOperationKind::WriteStdin,
execution: ExecutionWindow {
started_at_unix_ms: tool_start.wall_time_unix_ms,
@@ -553,7 +553,7 @@ fn invalid_write_stdin_arguments_remain_failed_tool_calls() -> anyhow::Result<()
ToolDispatchInvocation {
thread_id: ROOT_THREAD_ID.to_string(),
codex_turn_id: "turn-1".to_string(),
tool_call_id: "call-stdin".to_string(),
tool_call_id: "call-stdin".into(),
tool_name: "write_stdin".to_string(),
tool_namespace: None,
requester: ToolDispatchRequester::Model {
@@ -712,7 +712,7 @@ fn replay_write_stdin_result(
writer.append_with_context(
trace_context("turn-1"),
RawTraceEventPayload::ToolCallStarted {
tool_call_id: "tool-stdin".to_string(),
tool_call_id: "tool-stdin".into(),
model_visible_call_id: None,
code_mode_runtime_tool_id: Some("runtime-tool-1".to_string()),
requester: crate::raw_event::RawToolCallRequester::CodeCell {
@@ -728,7 +728,7 @@ fn replay_write_stdin_result(
RawPayloadKind::ToolResult,
&response,
move |response_payload| RawTraceEventPayload::ToolCallEnded {
tool_call_id: "tool-stdin".to_string(),
tool_call_id: "tool-stdin".into(),
status,
result_payload: Some(response_payload),
},
+10 -10
View File
@@ -275,7 +275,7 @@ impl ThreadTraceContext {
kind,
payload,
} => {
let tool_call_id = tool_call_id.to_owned();
let tool_call_id = ToolCallId::from(tool_call_id);
let _ = context.writer.event_with_payload(
envelope,
RawPayloadKind::ToolRuntimeEvent,
@@ -292,7 +292,7 @@ impl ThreadTraceContext {
status,
payload,
} => {
let tool_call_id = tool_call_id.to_owned();
let tool_call_id = ToolCallId::from(tool_call_id);
let _ = context.writer.event_with_payload(
envelope,
RawPayloadKind::ToolRuntimeEvent,
@@ -312,7 +312,7 @@ impl ThreadTraceContext {
pub fn record_mcp_tool_result(
&self,
codex_turn_id: &str,
tool_call_id: &str,
tool_call_id: &ToolCallId,
result: &Result<CallToolResult, String>,
) {
let ThreadTraceContextState::Enabled(context) = &self.state else {
@@ -322,7 +322,7 @@ impl ThreadTraceContext {
struct Payload<'a> {
result: &'a Result<CallToolResult, String>,
}
let tool_call_id = tool_call_id.to_owned();
let tool_call_id = tool_call_id.clone();
let status = if result.is_ok() {
ExecutionStatus::Completed
} else {
@@ -345,7 +345,7 @@ impl ThreadTraceContext {
&self,
default_turn_id: &str,
item: &ResponseItem,
source_tool_call_id: Option<&str>,
source_tool_call_id: Option<&ToolCallId>,
) {
let ThreadTraceContextState::Enabled(context) = &self.state else {
return;
@@ -353,7 +353,7 @@ impl ThreadTraceContext {
let Some(item_id) = item.id().map(ToString::to_string) else {
return;
};
let source_tool_call_id = source_tool_call_id.map(str::to_owned);
let source_tool_call_id = source_tool_call_id.cloned();
let accepted = move |agent_message_payload, tool_output_payload| {
RawTraceEventPayload::HistoryItemAccepted {
item_id,
@@ -401,8 +401,8 @@ impl ThreadTraceContext {
context.append_with_context_best_effort(
codex_turn_id.to_string(),
RawTraceEventPayload::StdinTargetResolved {
tool_call_id: tool_call_id.to_string(),
exec_tool_call_id: exec_tool_call_id.to_string(),
tool_call_id: tool_call_id.into(),
exec_tool_call_id: exec_tool_call_id.into(),
},
);
}
@@ -564,14 +564,14 @@ impl ThreadTraceContext {
/// Dispatch-level tool IDs remain compact and UI-friendly. This UUID is
/// deliberately separate: it is only for cross-process log joins where a
/// rollout-local counter would collide across samples.
pub fn start_mcp_call_trace(&self, tool_call_id: impl Into<ToolCallId>) -> McpCallTraceContext {
pub fn start_mcp_call_trace(&self, tool_call_id: &ToolCallId) -> McpCallTraceContext {
let ThreadTraceContextState::Enabled(context) = &self.state else {
return McpCallTraceContext::disabled();
};
let mcp_call_id = Uuid::new_v4().to_string();
let trace = McpCallTraceContext::enabled(mcp_call_id.clone());
context.append_best_effort(RawTraceEventPayload::McpToolCallCorrelationAssigned {
tool_call_id: tool_call_id.into(),
tool_call_id: tool_call_id.clone(),
mcp_call_id,
});
trace
+1 -1
View File
@@ -419,7 +419,7 @@ fn intercepted_exec_records_patch_without_a_terminal() -> anyhow::Result<()> {
let dispatch = trace.start_tool_dispatch_trace(|| Some(ToolDispatchInvocation {
thread_id: thread_id.to_string(),
codex_turn_id: "turn-1".to_string(),
tool_call_id: "patch-call".to_string(),
tool_call_id: "patch-call".into(),
tool_name: "exec_command".to_string(),
tool_namespace: None,
requester: ToolDispatchRequester::Model {
+6
View File
@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "tool-call-id",
crate_name = "codex_tool_call_id",
)
+15
View File
@@ -0,0 +1,15 @@
[package]
name = "codex-tool-call-id"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[lib]
test = false
doctest = false
[dependencies]
serde = { workspace = true, features = ["derive"] }
+53
View File
@@ -0,0 +1,53 @@
//! Identity of a tool invocation dispatched by Codex, including nested Code Mode calls.
//! The model-visible Responses ID and the JavaScript runtime's per-cell ID have separate roles.
use serde::Deserialize;
use serde::Serialize;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ToolCallId(String);
impl ToolCallId {
pub fn as_str(&self) -> &str {
&self.0
}
}
impl From<String> for ToolCallId {
fn from(id: String) -> Self {
Self(id)
}
}
impl From<&str> for ToolCallId {
fn from(id: &str) -> Self {
Self(id.to_owned())
}
}
impl std::borrow::Borrow<str> for ToolCallId {
fn borrow(&self) -> &str {
self.as_str()
}
}
impl std::fmt::Display for ToolCallId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
impl std::ops::Deref for ToolCallId {
type Target = str;
fn deref(&self) -> &Self::Target {
self.as_str()
}
}
impl From<ToolCallId> for String {
fn from(id: ToolCallId) -> Self {
id.0
}
}