mirror of
https://github.com/openai/codex.git
synced 2026-11-20 22:40:37 +00:00
Add parent turn id to Codex turn analytics
This commit is contained in:
@@ -380,6 +380,7 @@ fn sample_turn_resolved_config(thread_id: &str, turn_id: &str) -> TurnResolvedCo
|
||||
TurnResolvedConfigFact {
|
||||
turn_id: turn_id.to_string(),
|
||||
thread_id: thread_id.to_string(),
|
||||
parent_turn_id: None,
|
||||
num_input_images: 1,
|
||||
submission_type: None,
|
||||
ephemeral: false,
|
||||
@@ -3437,6 +3438,7 @@ fn turn_event_serializes_expected_shape() {
|
||||
initialization_mode: ThreadInitializationMode::New,
|
||||
subagent_source: None,
|
||||
parent_thread_id: None,
|
||||
parent_turn_id: None,
|
||||
model: Some("gpt-5".to_string()),
|
||||
model_provider: "openai".to_string(),
|
||||
sandbox_policy: Some("read_only"),
|
||||
@@ -3509,6 +3511,7 @@ fn turn_event_serializes_expected_shape() {
|
||||
"initialization_mode": "new",
|
||||
"subagent_source": null,
|
||||
"parent_thread_id": null,
|
||||
"parent_turn_id": null,
|
||||
"model": "gpt-5",
|
||||
"model_provider": "openai",
|
||||
"sandbox_policy": "read_only",
|
||||
@@ -3826,6 +3829,7 @@ async fn turn_lifecycle_emits_turn_event() {
|
||||
json!("session-thread-2")
|
||||
);
|
||||
assert_eq!(payload["event_params"]["turn_id"], json!("turn-2"));
|
||||
assert_eq!(payload["event_params"]["parent_turn_id"], json!(null));
|
||||
assert_eq!(
|
||||
payload["event_params"]["app_server_client"],
|
||||
json!({
|
||||
@@ -3875,6 +3879,50 @@ async fn turn_lifecycle_emits_turn_event() {
|
||||
assert_eq!(payload["event_params"]["total_tokens"], json!(321));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn turn_lifecycle_emits_parent_turn_id() {
|
||||
let mut reducer = AnalyticsReducer::default();
|
||||
let mut out = Vec::new();
|
||||
|
||||
ingest_turn_prerequisites(
|
||||
&mut reducer,
|
||||
&mut out,
|
||||
/*include_initialize*/ true,
|
||||
/*include_resolved_config*/ false,
|
||||
/*include_started*/ true,
|
||||
/*include_token_usage*/ true,
|
||||
)
|
||||
.await;
|
||||
let mut resolved_config = sample_turn_resolved_config("thread-2", "turn-2");
|
||||
resolved_config.parent_turn_id = Some("parent-turn-1".to_string());
|
||||
reducer
|
||||
.ingest(
|
||||
AnalyticsFact::Custom(CustomAnalyticsFact::TurnResolvedConfig(Box::new(
|
||||
resolved_config,
|
||||
))),
|
||||
&mut out,
|
||||
)
|
||||
.await;
|
||||
reducer
|
||||
.ingest(
|
||||
AnalyticsFact::Notification(Box::new(sample_turn_completed_notification(
|
||||
"thread-2",
|
||||
"turn-2",
|
||||
AppServerTurnStatus::Completed,
|
||||
/*codex_error_info*/ None,
|
||||
))),
|
||||
&mut out,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(out.len(), 1);
|
||||
let payload = serde_json::to_value(&out[0]).expect("serialize turn event");
|
||||
assert_eq!(
|
||||
payload["event_params"]["parent_turn_id"],
|
||||
json!("parent-turn-1")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn turn_event_counts_completed_tool_items() {
|
||||
let mut reducer = AnalyticsReducer::default();
|
||||
|
||||
@@ -854,6 +854,7 @@ pub(crate) struct CodexTurnEventParams {
|
||||
pub(crate) initialization_mode: ThreadInitializationMode,
|
||||
pub(crate) subagent_source: Option<String>,
|
||||
pub(crate) parent_thread_id: Option<String>,
|
||||
pub(crate) parent_turn_id: Option<String>,
|
||||
pub(crate) model: Option<String>,
|
||||
pub(crate) model_provider: String,
|
||||
pub(crate) sandbox_policy: Option<&'static str>,
|
||||
|
||||
@@ -66,6 +66,7 @@ pub enum TurnSubmissionType {
|
||||
pub struct TurnResolvedConfigFact {
|
||||
pub turn_id: String,
|
||||
pub thread_id: String,
|
||||
pub parent_turn_id: Option<String>,
|
||||
pub num_input_images: usize,
|
||||
pub submission_type: Option<TurnSubmissionType>,
|
||||
pub ephemeral: bool,
|
||||
|
||||
@@ -2467,6 +2467,7 @@ fn codex_turn_event_params(
|
||||
let TurnResolvedConfigFact {
|
||||
turn_id: _resolved_turn_id,
|
||||
thread_id: _resolved_thread_id,
|
||||
parent_turn_id,
|
||||
num_input_images: _resolved_num_input_images,
|
||||
submission_type,
|
||||
ephemeral,
|
||||
@@ -2509,6 +2510,7 @@ fn codex_turn_event_params(
|
||||
initialization_mode: thread_metadata.initialization_mode,
|
||||
subagent_source: thread_metadata.subagent_source.clone(),
|
||||
parent_thread_id: thread_metadata.parent_thread_id.clone(),
|
||||
parent_turn_id,
|
||||
model: Some(model),
|
||||
model_provider,
|
||||
sandbox_policy: Some(sandbox_policy_mode(
|
||||
|
||||
@@ -65,6 +65,7 @@ pub(crate) struct SpawnAgentOptions {
|
||||
pub(crate) fork_parent_spawn_call_id: Option<String>,
|
||||
pub(crate) fork_mode: Option<SpawnAgentForkMode>,
|
||||
pub(crate) parent_thread_id: Option<ThreadId>,
|
||||
pub(crate) parent_turn_id: Option<String>,
|
||||
pub(crate) environments: Option<Vec<TurnEnvironmentSelection>>,
|
||||
}
|
||||
|
||||
@@ -122,15 +123,26 @@ impl AgentControl {
|
||||
}
|
||||
|
||||
/// Send rich user input items to an existing agent thread.
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
pub(crate) async fn send_input(
|
||||
&self,
|
||||
agent_id: ThreadId,
|
||||
initial_operation: Op,
|
||||
) -> CodexResult<String> {
|
||||
self.send_input_with_parent_turn_id(agent_id, initial_operation, None)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn send_input_with_parent_turn_id(
|
||||
&self,
|
||||
agent_id: ThreadId,
|
||||
initial_operation: Op,
|
||||
parent_turn_id: Option<String>,
|
||||
) -> CodexResult<String> {
|
||||
let state = self.upgrade()?;
|
||||
self.ensure_execution_capacity_for_op(agent_id, &initial_operation)
|
||||
.await?;
|
||||
self.send_input_after_capacity_check(agent_id, &state, initial_operation)
|
||||
self.send_input_after_capacity_check(agent_id, &state, initial_operation, parent_turn_id)
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -139,6 +151,7 @@ impl AgentControl {
|
||||
agent_id: ThreadId,
|
||||
state: &Arc<ThreadManagerState>,
|
||||
initial_operation: Op,
|
||||
parent_turn_id: Option<String>,
|
||||
) -> CodexResult<String> {
|
||||
let last_task_message = match &initial_operation {
|
||||
Op::InterAgentCommunication { communication } => {
|
||||
@@ -150,7 +163,9 @@ impl AgentControl {
|
||||
.handle_thread_request_result(
|
||||
agent_id,
|
||||
state,
|
||||
state.send_op(agent_id, initial_operation).await,
|
||||
state
|
||||
.send_op_with_parent_turn_id(agent_id, initial_operation, parent_turn_id)
|
||||
.await,
|
||||
)
|
||||
.await;
|
||||
if result.is_ok() {
|
||||
|
||||
@@ -353,8 +353,13 @@ impl AgentControl {
|
||||
)
|
||||
.await;
|
||||
|
||||
self.send_input_after_capacity_check(new_thread.thread_id, &state, initial_operation)
|
||||
.await?;
|
||||
self.send_input_after_capacity_check(
|
||||
new_thread.thread_id,
|
||||
&state,
|
||||
initial_operation,
|
||||
options.parent_turn_id,
|
||||
)
|
||||
.await?;
|
||||
if multi_agent_version != MultiAgentVersion::V2 {
|
||||
let child_reference = agent_metadata
|
||||
.agent_path
|
||||
|
||||
@@ -234,6 +234,7 @@ pub(crate) async fn run_codex_thread_one_shot(
|
||||
id: "shutdown".to_string(),
|
||||
op: Op::Shutdown {},
|
||||
client_user_message_id: None,
|
||||
parent_turn_id: None,
|
||||
trace: None,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -132,6 +132,7 @@ async fn forward_ops_preserves_submission_trace_context() {
|
||||
id: "sub-1".to_string(),
|
||||
op: Op::Interrupt,
|
||||
client_user_message_id: None,
|
||||
parent_turn_id: None,
|
||||
trace: Some(codex_protocol::protocol::W3cTraceContext {
|
||||
traceparent: Some(
|
||||
"00-1234567890abcdef1234567890abcdef-1234567890abcdef-01".to_string(),
|
||||
|
||||
@@ -189,6 +189,16 @@ impl CodexThread {
|
||||
self.codex.submit(op).await
|
||||
}
|
||||
|
||||
pub(crate) async fn submit_with_parent_turn_id(
|
||||
&self,
|
||||
op: Op,
|
||||
parent_turn_id: Option<String>,
|
||||
) -> CodexResult<String> {
|
||||
self.codex
|
||||
.submit_with_parent_turn_id(op, parent_turn_id)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Returns the session telemetry handle for thread-scoped production instrumentation.
|
||||
pub fn session_telemetry(&self) -> SessionTelemetry {
|
||||
self.codex.session.services.session_telemetry.clone()
|
||||
|
||||
@@ -84,9 +84,17 @@ pub async fn user_input_or_turn(
|
||||
sess: &Arc<Session>,
|
||||
sub_id: String,
|
||||
op: Op,
|
||||
parent_turn_id: Option<String>,
|
||||
client_user_message_id: Option<String>,
|
||||
) {
|
||||
user_input_or_turn_inner(sess, sub_id, op, client_user_message_id).await;
|
||||
user_input_or_turn_inner(
|
||||
sess,
|
||||
sub_id,
|
||||
op,
|
||||
parent_turn_id,
|
||||
client_user_message_id,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
pub async fn update_thread_settings(
|
||||
@@ -184,6 +192,7 @@ pub(super) async fn user_input_or_turn_inner(
|
||||
sess: &Arc<Session>,
|
||||
sub_id: String,
|
||||
op: Op,
|
||||
parent_turn_id: Option<String>,
|
||||
client_user_message_id: Option<String>,
|
||||
) {
|
||||
let Op::UserInput {
|
||||
@@ -204,7 +213,10 @@ pub(super) async fn user_input_or_turn_inner(
|
||||
};
|
||||
updates.final_output_json_schema = Some(final_output_json_schema);
|
||||
|
||||
let Ok(current_context) = sess.new_turn_with_sub_id(sub_id.clone(), updates).await else {
|
||||
let Ok(current_context) = sess
|
||||
.new_turn_with_sub_id_and_parent_turn_id(sub_id.clone(), updates, parent_turn_id)
|
||||
.await
|
||||
else {
|
||||
// new_turn_with_sub_id already emits the error event.
|
||||
return;
|
||||
};
|
||||
@@ -751,8 +763,14 @@ pub(super) async fn submission_loop(
|
||||
false
|
||||
}
|
||||
Op::UserInput { .. } => {
|
||||
user_input_or_turn(&sess, sub.id.clone(), sub.op, sub.client_user_message_id)
|
||||
.await;
|
||||
user_input_or_turn(
|
||||
&sess,
|
||||
sub.id.clone(),
|
||||
sub.op,
|
||||
sub.parent_turn_id,
|
||||
sub.client_user_message_id,
|
||||
)
|
||||
.await;
|
||||
false
|
||||
}
|
||||
Op::ThreadSettings { thread_settings } => {
|
||||
|
||||
@@ -92,6 +92,15 @@ impl InputQueue {
|
||||
.any(|mail| mail.trigger_turn)
|
||||
}
|
||||
|
||||
pub(crate) async fn next_trigger_turn_parent_turn_id(&self) -> Option<String> {
|
||||
self.mailbox_pending_mails
|
||||
.lock()
|
||||
.await
|
||||
.iter()
|
||||
.find(|mail| mail.trigger_turn)
|
||||
.and_then(|mail| mail.parent_turn_id.clone())
|
||||
}
|
||||
|
||||
pub(crate) async fn drain_mailbox_input_items(&self) -> Vec<TurnInput> {
|
||||
self.mailbox_pending_mails
|
||||
.lock()
|
||||
@@ -417,4 +426,34 @@ mod tests {
|
||||
.await;
|
||||
assert!(input_queue.has_trigger_turn_mailbox_items().await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn input_queue_tracks_next_trigger_turn_parent_turn_id() {
|
||||
let input_queue = InputQueue::new();
|
||||
|
||||
input_queue
|
||||
.enqueue_mailbox_communication(make_mail(
|
||||
AgentPath::root(),
|
||||
AgentPath::try_from("/root/worker").expect("agent path"),
|
||||
"queued",
|
||||
/*trigger_turn*/ false,
|
||||
))
|
||||
.await;
|
||||
input_queue
|
||||
.enqueue_mailbox_communication(
|
||||
make_mail(
|
||||
AgentPath::root(),
|
||||
AgentPath::try_from("/root/worker").expect("agent path"),
|
||||
"wake",
|
||||
/*trigger_turn*/ true,
|
||||
)
|
||||
.with_parent_turn_id(Some("parent-turn-1".to_string())),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
input_queue.next_trigger_turn_parent_turn_id().await,
|
||||
Some("parent-turn-1".to_string())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -692,19 +692,39 @@ impl Codex {
|
||||
|
||||
/// Submit the `op` wrapped in a `Submission` with a unique ID.
|
||||
pub async fn submit(&self, op: Op) -> CodexResult<String> {
|
||||
self.submit_with_trace(op, /*trace*/ None).await
|
||||
self.submit_with_parent_turn_id(op, None).await
|
||||
}
|
||||
|
||||
pub(crate) async fn submit_with_parent_turn_id(
|
||||
&self,
|
||||
op: Op,
|
||||
parent_turn_id: Option<String>,
|
||||
) -> CodexResult<String> {
|
||||
self.submit_with_trace_and_parent_turn_id(op, /*trace*/ None, parent_turn_id)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn submit_with_trace(
|
||||
&self,
|
||||
op: Op,
|
||||
trace: Option<W3cTraceContext>,
|
||||
) -> CodexResult<String> {
|
||||
self.submit_with_trace_and_parent_turn_id(op, trace, None)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn submit_with_trace_and_parent_turn_id(
|
||||
&self,
|
||||
op: Op,
|
||||
trace: Option<W3cTraceContext>,
|
||||
parent_turn_id: Option<String>,
|
||||
) -> CodexResult<String> {
|
||||
let id = Uuid::now_v7().to_string();
|
||||
let sub = Submission {
|
||||
id: id.clone(),
|
||||
op,
|
||||
client_user_message_id: None,
|
||||
parent_turn_id,
|
||||
trace,
|
||||
};
|
||||
self.submit_with_id(sub).await?;
|
||||
@@ -723,6 +743,7 @@ impl Codex {
|
||||
id: id.clone(),
|
||||
op,
|
||||
client_user_message_id,
|
||||
parent_turn_id: None,
|
||||
trace,
|
||||
};
|
||||
self.submit_with_id(sub).await?;
|
||||
@@ -1145,6 +1166,7 @@ impl Session {
|
||||
additional_context: Default::default(),
|
||||
thread_settings: Default::default(),
|
||||
},
|
||||
/*parent_turn_id*/ None,
|
||||
/*client_user_message_id*/ None,
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -114,6 +114,7 @@ pub(super) async fn spawn_review_thread(
|
||||
reasoning_summary,
|
||||
session_source,
|
||||
parent_thread_id: parent_turn_context.parent_thread_id,
|
||||
parent_turn_id: parent_turn_context.parent_turn_id.clone(),
|
||||
environments: parent_turn_context.environments.clone(),
|
||||
available_models,
|
||||
unified_exec_shell_mode,
|
||||
|
||||
@@ -5074,6 +5074,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
|
||||
resolved_turn_environments,
|
||||
session_configuration.cwd().clone(),
|
||||
"turn_id".to_string(),
|
||||
/*parent_turn_id*/ None,
|
||||
skills_snapshot,
|
||||
);
|
||||
|
||||
@@ -6020,6 +6021,7 @@ async fn submit_with_id_captures_current_span_trace_context() {
|
||||
id: "sub-1".into(),
|
||||
op: Op::Interrupt,
|
||||
client_user_message_id: None,
|
||||
parent_turn_id: None,
|
||||
trace: None,
|
||||
})
|
||||
.await
|
||||
@@ -6092,6 +6094,7 @@ fn submission_dispatch_span_prefers_submission_trace_context() {
|
||||
id: "sub-1".into(),
|
||||
op: Op::Interrupt,
|
||||
client_user_message_id: None,
|
||||
parent_turn_id: None,
|
||||
trace: Some(submission_trace),
|
||||
})
|
||||
});
|
||||
@@ -6119,6 +6122,7 @@ fn submission_dispatch_span_uses_debug_for_realtime_audio() {
|
||||
},
|
||||
}),
|
||||
client_user_message_id: None,
|
||||
parent_turn_id: None,
|
||||
trace: None,
|
||||
});
|
||||
|
||||
@@ -6184,6 +6188,7 @@ async fn user_turn_updates_approvals_reviewer() {
|
||||
..Default::default()
|
||||
},
|
||||
},
|
||||
/*parent_turn_id*/ None,
|
||||
/*client_user_message_id*/ None,
|
||||
)
|
||||
.await;
|
||||
@@ -6195,6 +6200,24 @@ async fn user_turn_updates_approvals_reviewer() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn new_turn_carries_parent_turn_id() {
|
||||
let (session, _turn_context, _rx) = make_session_and_context_with_rx().await;
|
||||
let turn_context = session
|
||||
.new_turn_with_sub_id_and_parent_turn_id(
|
||||
"child-turn".to_string(),
|
||||
SessionSettingsUpdate::default(),
|
||||
Some("parent-turn-1".to_string()),
|
||||
)
|
||||
.await
|
||||
.expect("child turn context should build");
|
||||
|
||||
assert_eq!(
|
||||
turn_context.parent_turn_id.as_deref(),
|
||||
Some("parent-turn-1")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn turn_environments_set_primary_environment() {
|
||||
let (session, _turn_context, _rx) = make_session_and_context_with_rx().await;
|
||||
@@ -6432,6 +6455,7 @@ async fn spawn_task_turn_span_inherits_dispatch_trace_context() {
|
||||
id: "sub-1".into(),
|
||||
op: Op::Interrupt,
|
||||
client_user_message_id: None,
|
||||
parent_turn_id: None,
|
||||
trace: Some(submission_trace.clone()),
|
||||
});
|
||||
let dispatch_span_id = dispatch_span.context().span().span_context().span_id();
|
||||
@@ -7117,6 +7141,7 @@ where
|
||||
resolved_turn_environments,
|
||||
session_configuration.cwd().clone(),
|
||||
"turn_id".to_string(),
|
||||
/*parent_turn_id*/ None,
|
||||
skills_snapshot,
|
||||
));
|
||||
|
||||
|
||||
@@ -697,6 +697,7 @@ async fn track_turn_resolved_config_analytics(
|
||||
.track_turn_resolved_config(TurnResolvedConfigFact {
|
||||
turn_id: turn_context.sub_id.clone(),
|
||||
thread_id: sess.thread_id.to_string(),
|
||||
parent_turn_id: turn_context.parent_turn_id.clone(),
|
||||
num_input_images: input
|
||||
.iter()
|
||||
.filter_map(|item| match item {
|
||||
|
||||
@@ -113,6 +113,7 @@ pub struct TurnContext {
|
||||
pub(crate) reasoning_summary: ReasoningSummaryConfig,
|
||||
pub(crate) session_source: SessionSource,
|
||||
pub(crate) parent_thread_id: Option<ThreadId>,
|
||||
pub(crate) parent_turn_id: Option<String>,
|
||||
pub(crate) environments: TurnEnvironmentSnapshot,
|
||||
/// The session's absolute working directory. All relative paths provided
|
||||
/// by the model as well as sandbox policies are resolved against this path
|
||||
@@ -267,6 +268,7 @@ impl TurnContext {
|
||||
reasoning_summary: self.reasoning_summary,
|
||||
session_source: self.session_source.clone(),
|
||||
parent_thread_id: self.parent_thread_id,
|
||||
parent_turn_id: self.parent_turn_id.clone(),
|
||||
environments: self.environments.clone(),
|
||||
#[allow(deprecated)]
|
||||
cwd: self.cwd.clone(),
|
||||
@@ -493,6 +495,7 @@ impl Session {
|
||||
environments: TurnEnvironmentSnapshot,
|
||||
cwd: AbsolutePathBuf,
|
||||
sub_id: String,
|
||||
parent_turn_id: Option<String>,
|
||||
skills_snapshot: HostSkillsSnapshot,
|
||||
) -> TurnContext {
|
||||
let reasoning_effort = session_configuration.collaboration_mode.reasoning_effort();
|
||||
@@ -550,6 +553,7 @@ impl Session {
|
||||
reasoning_summary,
|
||||
session_source,
|
||||
parent_thread_id: session_configuration.parent_thread_id,
|
||||
parent_turn_id,
|
||||
environments,
|
||||
#[allow(deprecated)]
|
||||
cwd,
|
||||
@@ -582,10 +586,21 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
pub(crate) async fn new_turn_with_sub_id(
|
||||
&self,
|
||||
sub_id: String,
|
||||
updates: SessionSettingsUpdate,
|
||||
) -> CodexResult<Arc<TurnContext>> {
|
||||
self.new_turn_with_sub_id_and_parent_turn_id(sub_id, updates, None)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn new_turn_with_sub_id_and_parent_turn_id(
|
||||
&self,
|
||||
sub_id: String,
|
||||
updates: SessionSettingsUpdate,
|
||||
parent_turn_id: Option<String>,
|
||||
) -> CodexResult<Arc<TurnContext>> {
|
||||
let notify_config_contributors = !self.services.extensions.config_contributors().is_empty();
|
||||
let update_result: CodexResult<_> = {
|
||||
@@ -647,6 +662,7 @@ impl Session {
|
||||
sub_id,
|
||||
session_configuration,
|
||||
updates.final_output_json_schema,
|
||||
parent_turn_id,
|
||||
)
|
||||
.await)
|
||||
}
|
||||
@@ -656,11 +672,13 @@ impl Session {
|
||||
sub_id: String,
|
||||
session_configuration: SessionConfiguration,
|
||||
final_output_json_schema: Option<Option<Value>>,
|
||||
parent_turn_id: Option<String>,
|
||||
) -> Arc<TurnContext> {
|
||||
self.new_turn_context_from_configuration(
|
||||
sub_id,
|
||||
session_configuration,
|
||||
final_output_json_schema,
|
||||
parent_turn_id,
|
||||
TurnMultiAgentRuntime::ResolveAndStore,
|
||||
)
|
||||
.await
|
||||
@@ -675,6 +693,7 @@ impl Session {
|
||||
sub_id,
|
||||
session_configuration,
|
||||
/*final_output_json_schema*/ None,
|
||||
/*parent_turn_id*/ None,
|
||||
TurnMultiAgentRuntime::Preview,
|
||||
)
|
||||
.await
|
||||
@@ -686,6 +705,7 @@ impl Session {
|
||||
sub_id: String,
|
||||
session_configuration: SessionConfiguration,
|
||||
final_output_json_schema: Option<Option<Value>>,
|
||||
parent_turn_id: Option<String>,
|
||||
multi_agent_runtime: TurnMultiAgentRuntime,
|
||||
) -> Arc<TurnContext> {
|
||||
let turn_environments = self.services.turn_environments.snapshot().await;
|
||||
@@ -763,6 +783,7 @@ impl Session {
|
||||
turn_environments,
|
||||
cwd,
|
||||
sub_id,
|
||||
parent_turn_id,
|
||||
skills_snapshot,
|
||||
);
|
||||
turn_context.realtime_active = self.conversation.running_state().await.is_some();
|
||||
@@ -802,11 +823,21 @@ impl Session {
|
||||
}
|
||||
|
||||
pub(crate) async fn new_default_turn_with_sub_id(&self, sub_id: String) -> Arc<TurnContext> {
|
||||
self.new_default_turn_with_sub_id_and_parent_turn_id(sub_id, /*parent_turn_id*/ None)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn new_default_turn_with_sub_id_and_parent_turn_id(
|
||||
&self,
|
||||
sub_id: String,
|
||||
parent_turn_id: Option<String>,
|
||||
) -> Arc<TurnContext> {
|
||||
let session_configuration = self.default_turn_configuration().await;
|
||||
self.new_turn_from_configuration(
|
||||
sub_id,
|
||||
session_configuration,
|
||||
/*final_output_json_schema*/ None,
|
||||
parent_turn_id,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -476,7 +476,10 @@ impl Session {
|
||||
*active_turn = Some(ActiveTurn::default());
|
||||
}
|
||||
|
||||
let turn_context = self.new_default_turn_with_sub_id(sub_id).await;
|
||||
let parent_turn_id = self.input_queue.next_trigger_turn_parent_turn_id().await;
|
||||
let turn_context = self
|
||||
.new_default_turn_with_sub_id_and_parent_turn_id(sub_id, parent_turn_id)
|
||||
.await;
|
||||
self.maybe_emit_unknown_model_warning_for_turn(turn_context.as_ref())
|
||||
.await;
|
||||
self.start_task(turn_context, Vec::new(), RegularTask::new())
|
||||
|
||||
@@ -88,7 +88,7 @@ const THREAD_CREATED_CHANNEL_CAPACITY: usize = 1024;
|
||||
/// must not be toggled.
|
||||
static FORCE_TEST_THREAD_MANAGER_BEHAVIOR: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
type CapturedOps = Vec<(ThreadId, Op)>;
|
||||
type CapturedOps = Vec<(ThreadId, Op, Option<String>)>;
|
||||
type SharedCapturedOps = Arc<std::sync::Mutex<CapturedOps>>;
|
||||
|
||||
pub(crate) fn set_thread_manager_test_mode_for_tests(enabled: bool) {
|
||||
@@ -976,6 +976,21 @@ impl ThreadManager {
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn captured_ops(&self) -> Vec<(ThreadId, Op)> {
|
||||
self.state
|
||||
.ops_log
|
||||
.as_ref()
|
||||
.and_then(|ops_log| {
|
||||
ops_log.lock().ok().map(|log| {
|
||||
log.iter()
|
||||
.map(|(thread_id, op, _parent_turn_id)| (*thread_id, op.clone()))
|
||||
.collect()
|
||||
})
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn captured_ops_with_parent_turn_ids(&self) -> Vec<(ThreadId, Op, Option<String>)> {
|
||||
self.state
|
||||
.ops_log
|
||||
.as_ref()
|
||||
@@ -1057,13 +1072,22 @@ impl ThreadManagerState {
|
||||
|
||||
/// Send an operation to a thread by ID.
|
||||
pub(crate) async fn send_op(&self, thread_id: ThreadId, op: Op) -> CodexResult<String> {
|
||||
self.send_op_with_parent_turn_id(thread_id, op, None).await
|
||||
}
|
||||
|
||||
pub(crate) async fn send_op_with_parent_turn_id(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
op: Op,
|
||||
parent_turn_id: Option<String>,
|
||||
) -> CodexResult<String> {
|
||||
let thread = self.get_thread(thread_id).await?;
|
||||
if let Some(ops_log) = &self.ops_log
|
||||
&& let Ok(mut log) = ops_log.lock()
|
||||
{
|
||||
log.push((thread_id, op.clone()));
|
||||
log.push((thread_id, op.clone(), parent_turn_id.clone()));
|
||||
}
|
||||
thread.submit(op).await
|
||||
thread.submit_with_parent_turn_id(op, parent_turn_id).await
|
||||
}
|
||||
|
||||
/// Remove a thread from the manager by ID, returning it when present.
|
||||
|
||||
@@ -66,6 +66,8 @@ impl Handler {
|
||||
.await
|
||||
.map_err(|err| collab_agent_error(receiver_thread_id, err))?;
|
||||
}
|
||||
let parent_turn_id =
|
||||
direct_parent_turn_id_for_receiver(&session, turn.as_ref(), receiver_thread_id).await;
|
||||
session
|
||||
.send_event(
|
||||
&turn,
|
||||
@@ -81,7 +83,7 @@ impl Handler {
|
||||
.await;
|
||||
let agent_control = session.services.agent_control.clone();
|
||||
let result = agent_control
|
||||
.send_input(receiver_thread_id, input_items)
|
||||
.send_input_with_parent_turn_id(receiver_thread_id, input_items, parent_turn_id)
|
||||
.await
|
||||
.map_err(|err| collab_agent_error(receiver_thread_id, err));
|
||||
let status = session
|
||||
|
||||
@@ -131,6 +131,7 @@ async fn handle_spawn_agent(
|
||||
fork_parent_spawn_call_id: args.fork_context.then(|| call_id.clone()),
|
||||
fork_mode: args.fork_context.then_some(SpawnAgentForkMode::FullHistory),
|
||||
parent_thread_id: Some(session.thread_id),
|
||||
parent_turn_id: Some(turn.sub_id.clone()),
|
||||
environments: Some(turn.environments.to_selections()),
|
||||
},
|
||||
))
|
||||
|
||||
@@ -194,6 +194,20 @@ pub(crate) fn parse_collab_input(
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn direct_parent_turn_id_for_receiver(
|
||||
session: &Session,
|
||||
turn: &TurnContext,
|
||||
receiver_thread_id: ThreadId,
|
||||
) -> Option<String> {
|
||||
session
|
||||
.services
|
||||
.agent_control
|
||||
.get_agent_config_snapshot(receiver_thread_id)
|
||||
.await
|
||||
.filter(|snapshot| snapshot.parent_thread_id == Some(session.thread_id))
|
||||
.map(|_| turn.sub_id.clone())
|
||||
}
|
||||
|
||||
/// Builds the base config snapshot for a newly spawned sub-agent.
|
||||
///
|
||||
/// The returned config starts from the parent's effective config and then refreshes the
|
||||
|
||||
@@ -306,6 +306,64 @@ async fn spawn_agent_uses_explorer_role_and_preserves_approval_policy() {
|
||||
assert_eq!(snapshot.model_provider_id, "ollama");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn spawn_agent_options_forward_parent_turn_id() {
|
||||
let (mut session, turn) = make_session_and_context().await;
|
||||
let parent_turn_id = turn.sub_id.clone();
|
||||
let manager = thread_manager();
|
||||
let root = manager
|
||||
.start_thread((*turn.config).clone())
|
||||
.await
|
||||
.expect("root thread should start");
|
||||
session.services.agent_control = manager.agent_control();
|
||||
let child = session
|
||||
.services
|
||||
.agent_control
|
||||
.spawn_agent_with_metadata(
|
||||
(*turn.config).clone(),
|
||||
Op::ThreadSettings {
|
||||
thread_settings: Default::default(),
|
||||
},
|
||||
Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
|
||||
parent_thread_id: root.thread_id,
|
||||
depth: 1,
|
||||
agent_path: Some(AgentPath::try_from("/root/worker").expect("agent path")),
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
})),
|
||||
crate::agent::control::SpawnAgentOptions {
|
||||
parent_thread_id: Some(root.thread_id),
|
||||
parent_turn_id: Some(parent_turn_id.clone()),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("child thread should spawn");
|
||||
let child_thread = manager
|
||||
.get_thread(child.thread_id)
|
||||
.await
|
||||
.expect("child thread should exist");
|
||||
assert_eq!(
|
||||
manager
|
||||
.captured_ops_with_parent_turn_ids()
|
||||
.into_iter()
|
||||
.find_map(|(thread_id, op, captured_parent_turn_id)| {
|
||||
(thread_id == child.thread_id && matches!(op, Op::ThreadSettings { .. }))
|
||||
.then_some(captured_parent_turn_id)
|
||||
}),
|
||||
Some(Some(parent_turn_id))
|
||||
);
|
||||
|
||||
child_thread
|
||||
.submit(Op::Shutdown {})
|
||||
.await
|
||||
.expect("shutdown should submit");
|
||||
root.thread
|
||||
.submit(Op::Shutdown {})
|
||||
.await
|
||||
.expect("shutdown should submit");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn spawn_agent_fork_context_rejects_agent_type_override() {
|
||||
let (mut session, mut turn) = make_session_and_context().await;
|
||||
@@ -1983,6 +2041,7 @@ async fn multi_agent_v2_followup_task_completion_notifies_parent_on_every_turn()
|
||||
session.thread_id = root.thread_id;
|
||||
let session = Arc::new(session);
|
||||
let turn = Arc::new(turn);
|
||||
let parent_turn_id = turn.sub_id.clone();
|
||||
|
||||
SpawnAgentHandlerV2::default()
|
||||
.handle(invocation(
|
||||
@@ -2036,6 +2095,16 @@ async fn multi_agent_v2_followup_task_completion_notifies_parent_on_every_turn()
|
||||
))
|
||||
.await
|
||||
.expect("followup_task should succeed");
|
||||
assert!(manager.captured_ops().iter().any(|(id, op)| {
|
||||
*id == agent_id
|
||||
&& matches!(
|
||||
op,
|
||||
Op::InterAgentCommunication { communication }
|
||||
if communication.parent_turn_id.as_deref() == Some(parent_turn_id.as_str())
|
||||
&& communication.encrypted_content.as_deref() == Some("continue")
|
||||
&& communication.trigger_turn
|
||||
)
|
||||
}));
|
||||
|
||||
assert!(manager.captured_ops().iter().any(|(id, op)| {
|
||||
*id == agent_id
|
||||
@@ -2734,6 +2803,63 @@ async fn send_input_accepts_structured_items() {
|
||||
.expect("shutdown should submit");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn direct_parent_turn_id_for_receiver_identifies_direct_child() {
|
||||
let (mut session, turn) = make_session_and_context().await;
|
||||
let parent_turn_id = turn.sub_id.clone();
|
||||
let manager = thread_manager();
|
||||
let root = manager
|
||||
.start_thread((*turn.config).clone())
|
||||
.await
|
||||
.expect("root thread should start");
|
||||
session.services.agent_control = manager.agent_control();
|
||||
session.thread_id = root.thread_id;
|
||||
let child = session
|
||||
.services
|
||||
.agent_control
|
||||
.spawn_agent_with_metadata(
|
||||
(*turn.config).clone(),
|
||||
Op::ThreadSettings {
|
||||
thread_settings: Default::default(),
|
||||
},
|
||||
Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
|
||||
parent_thread_id: root.thread_id,
|
||||
depth: 1,
|
||||
agent_path: Some(AgentPath::try_from("/root/worker").expect("agent path")),
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
})),
|
||||
crate::agent::control::SpawnAgentOptions {
|
||||
parent_thread_id: Some(root.thread_id),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("child thread should spawn");
|
||||
let child_thread = manager
|
||||
.get_thread(child.thread_id)
|
||||
.await
|
||||
.expect("child thread should exist");
|
||||
|
||||
assert_eq!(
|
||||
direct_parent_turn_id_for_receiver(&session, &turn, child.thread_id).await,
|
||||
Some(parent_turn_id)
|
||||
);
|
||||
assert_eq!(
|
||||
direct_parent_turn_id_for_receiver(&session, &turn, root.thread_id).await,
|
||||
None
|
||||
);
|
||||
|
||||
child_thread
|
||||
.submit(Op::Shutdown {})
|
||||
.await
|
||||
.expect("shutdown should submit");
|
||||
root.thread
|
||||
.submit(Op::Shutdown {})
|
||||
.await
|
||||
.expect("shutdown should submit");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resume_agent_rejects_invalid_id() {
|
||||
let (session, turn) = make_session_and_context().await;
|
||||
|
||||
@@ -44,6 +44,7 @@ pub(super) fn communication_from_tool_message(
|
||||
author: AgentPath,
|
||||
recipient: AgentPath,
|
||||
message: String,
|
||||
parent_turn_id: Option<String>,
|
||||
) -> InterAgentCommunication {
|
||||
InterAgentCommunication::new_encrypted(
|
||||
author,
|
||||
@@ -52,4 +53,5 @@ pub(super) fn communication_from_tool_message(
|
||||
message,
|
||||
/*trigger_turn*/ true,
|
||||
)
|
||||
.with_parent_turn_id(parent_turn_id)
|
||||
}
|
||||
|
||||
@@ -100,8 +100,18 @@ pub(crate) async fn handle_message_string_tool(
|
||||
.session_source
|
||||
.get_agent_path()
|
||||
.unwrap_or_else(AgentPath::root);
|
||||
let mut communication =
|
||||
communication_from_tool_message(author, receiver_agent_path.clone(), message);
|
||||
let parent_turn_id = match mode {
|
||||
MessageDeliveryMode::QueueOnly => None,
|
||||
MessageDeliveryMode::TriggerTurn => {
|
||||
direct_parent_turn_id_for_receiver(&session, turn.as_ref(), receiver_thread_id).await
|
||||
}
|
||||
};
|
||||
let mut communication = communication_from_tool_message(
|
||||
author,
|
||||
receiver_agent_path.clone(),
|
||||
message,
|
||||
parent_turn_id,
|
||||
);
|
||||
communication
|
||||
.metadata
|
||||
.get_or_insert_with(ResponseItemMetadata::default)
|
||||
|
||||
@@ -118,8 +118,12 @@ async fn handle_spawn_agent(
|
||||
.session_source
|
||||
.get_agent_path()
|
||||
.unwrap_or_else(AgentPath::root);
|
||||
let mut communication =
|
||||
communication_from_tool_message(author, new_agent_path.clone(), message);
|
||||
let mut communication = communication_from_tool_message(
|
||||
author,
|
||||
new_agent_path.clone(),
|
||||
message,
|
||||
Some(turn.sub_id.clone()),
|
||||
);
|
||||
communication
|
||||
.metadata
|
||||
.get_or_insert_with(ResponseItemMetadata::default)
|
||||
@@ -133,6 +137,7 @@ async fn handle_spawn_agent(
|
||||
fork_parent_spawn_call_id: fork_mode.as_ref().map(|_| call_id.clone()),
|
||||
fork_mode,
|
||||
parent_thread_id: Some(session.thread_id),
|
||||
parent_turn_id: Some(turn.sub_id.clone()),
|
||||
environments: Some(turn.environments.to_selections()),
|
||||
},
|
||||
),
|
||||
|
||||
@@ -114,6 +114,7 @@ pub async fn run_codex_tool_session(
|
||||
thread_settings: Default::default(),
|
||||
},
|
||||
client_user_message_id: None,
|
||||
parent_turn_id: None,
|
||||
trace: None,
|
||||
};
|
||||
|
||||
|
||||
@@ -545,6 +545,7 @@ impl MessageProcessor {
|
||||
id: request_id_string,
|
||||
op: codex_protocol::protocol::Op::Interrupt,
|
||||
client_user_message_id: None,
|
||||
parent_turn_id: None,
|
||||
trace: None,
|
||||
})
|
||||
.await
|
||||
|
||||
@@ -154,6 +154,8 @@ pub struct Submission {
|
||||
pub op: Op,
|
||||
/// Client-provided id for the user message represented by `Op::UserInput`.
|
||||
pub client_user_message_id: Option<String>,
|
||||
/// Direct parent-thread turn that triggered this child turn, when known.
|
||||
pub parent_turn_id: Option<String>,
|
||||
/// Optional W3C trace carrier propagated across async submission handoffs.
|
||||
pub trace: Option<W3cTraceContext>,
|
||||
}
|
||||
@@ -687,6 +689,11 @@ pub struct InterAgentCommunication {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[ts(optional)]
|
||||
pub metadata: Option<ResponseItemMetadata>,
|
||||
/// Runtime-only direct parent turn lineage for analytics turn construction.
|
||||
#[serde(skip)]
|
||||
#[schemars(skip)]
|
||||
#[ts(skip)]
|
||||
pub parent_turn_id: Option<String>,
|
||||
pub trigger_turn: bool,
|
||||
}
|
||||
|
||||
@@ -705,6 +712,7 @@ impl InterAgentCommunication {
|
||||
content,
|
||||
encrypted_content: None,
|
||||
metadata: None,
|
||||
parent_turn_id: None,
|
||||
trigger_turn,
|
||||
}
|
||||
}
|
||||
@@ -723,10 +731,16 @@ impl InterAgentCommunication {
|
||||
content: String::new(),
|
||||
encrypted_content: Some(encrypted_content),
|
||||
metadata: None,
|
||||
parent_turn_id: None,
|
||||
trigger_turn,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_parent_turn_id(mut self, parent_turn_id: Option<String>) -> Self {
|
||||
self.parent_turn_id = parent_turn_id;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn to_response_input_item(&self) -> ResponseInputItem {
|
||||
ResponseInputItem::Message {
|
||||
role: "assistant".to_string(),
|
||||
@@ -4256,11 +4270,13 @@ mod tests {
|
||||
content: "review the diff".to_string(),
|
||||
encrypted_content: None,
|
||||
metadata: None,
|
||||
parent_turn_id: Some("parent-turn-1".to_string()),
|
||||
trigger_turn: true,
|
||||
};
|
||||
|
||||
let response_input_item = communication.to_response_input_item();
|
||||
assert_eq!(
|
||||
communication.to_response_input_item(),
|
||||
response_input_item,
|
||||
ResponseInputItem::Message {
|
||||
role: "assistant".to_string(),
|
||||
content: vec![ContentItem::OutputText {
|
||||
@@ -4269,6 +4285,13 @@ mod tests {
|
||||
phase: Some(MessagePhase::Commentary),
|
||||
}
|
||||
);
|
||||
let ResponseInputItem::Message { content, .. } = response_input_item else {
|
||||
panic!("inter-agent communication should serialize as a message");
|
||||
};
|
||||
let [ContentItem::OutputText { text }] = content.as_slice() else {
|
||||
panic!("inter-agent communication should serialize one text item");
|
||||
};
|
||||
assert!(!text.contains("parent_turn_id"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user