Preserve client attribution when spawning subagents (#62072)

## Why

Delegated work should retain client attribution such as `cost_center` from the turn that requested it, even when a yielded code-mode cell spawns its child after a newer parent turn starts.

## What changed

Capture client metadata from the originating turn and apply it to the child's initial turn in both legacy and v2 agent spawning. Children and grandchildren retain the captured values when the parent is later steered with updated metadata.

Exclude `misalignment_override`, `parent_response_id`, and `mcp_request_meta` from inheritance, while preserving each child's own thread and turn identifiers.

## Testing

Add coverage for metadata filtering and snapshot isolation, legacy and v2 spawning with fresh or forked history, grandchild inheritance, and spawning from a yielded code-mode cell after the parent advances to another turn.

GitOrigin-RevId: 8c378c49239ccfac03deb2b793fc69aba1d41644
This commit is contained in:
jif
2026-11-17 16:15:55 +00:00
committed by copyberry
parent cac9284d24
commit 02d60fb5cc
11 changed files with 353 additions and 4 deletions
+1
View File
@@ -994,6 +994,7 @@ impl LocalAgentControl {
turn_trigger: options.turn_trigger,
root_turn_id: options.root_turn_id,
cyber_access_program,
inherited_client_metadata: options.inherited_client_metadata,
..Default::default()
};
let input_admission_started_at = Instant::now();
+3
View File
@@ -7,6 +7,7 @@ use codex_protocol::AgentPath;
use codex_protocol::ThreadId;
use codex_protocol::protocol::AgentStatus;
use codex_protocol::turn_input::CyberAccessProgram;
use std::collections::HashMap;
/// Registry identity shared by loaded and unloaded agents.
/// Registered agents have an `agent_id`; a reserved spawn can still be awaiting its ID.
@@ -41,6 +42,8 @@ pub struct SpawnAgentOptions {
/// Attribute delegated usage to the turn that initiated it.
pub turn_trigger: Option<String>,
pub root_turn_id: Option<String>,
/// Client attribution captured from the turn that requested the child.
pub inherited_client_metadata: HashMap<String, String>,
/// Inheritable bindings captured by the step that requested the child.
pub environments: Option<TurnEnvironmentSnapshot>,
/// Plugin choices from the turn requesting the child. Omission inherits the parent's
+7
View File
@@ -160,6 +160,7 @@ impl PreparedTurnInputSettings {
initiating_agent_path,
root_turn_id,
cyber_access_program,
inherited_client_metadata,
} = self.start_options;
let helper_admission =
if kind == TurnStartKind::User && turn_trigger.as_deref() != Some("queue") {
@@ -203,6 +204,12 @@ impl PreparedTurnInputSettings {
let Some((turn_context, settings_snapshot)) = turn_context else {
return Ok(None);
};
turn_context
.turn_metadata_state
.update_responsesapi_client_metadata(ResponsesApiClientMetadataUpdate {
replacement: Some(inherited_client_metadata),
..Default::default()
});
if let Some(turn_trigger) = turn_trigger {
turn_context
.turn_metadata_state
+8
View File
@@ -641,6 +641,14 @@ impl Session {
if let Some(id) = start_options.root_turn_id {
turn_context.turn_metadata_state.set_root_turn_id(id);
}
turn_context
.turn_metadata_state
.update_responsesapi_client_metadata(
codex_protocol::turn_input::ResponsesApiClientMetadataUpdate {
replacement: Some(start_options.inherited_client_metadata),
..Default::default()
},
);
self.maybe_emit_model_warnings_for_turn(turn_context.as_ref())
.await;
// Context construction can outlive an interrupt or replacement. Do not let
+1
View File
@@ -204,6 +204,7 @@ pub(crate) async fn prepare(
parent_thread_id: Some(session.thread_id),
parent_turn_id: Some(turn.sub_id.clone()),
root_turn_id: turn.turn_metadata_state.root_turn_id(),
inherited_client_metadata: turn.turn_metadata_state.client_metadata_for_child(),
turn_trigger: turn.turn_metadata_state.current_turn_trigger(),
environments: Some(step_context.inherited_environments.clone()),
disabled_plugin_ids: Some(turn.disabled_plugin_ids.clone()),
@@ -138,6 +138,7 @@ async fn handle_spawn_agent(
parent_thread_id: Some(session.thread_id),
parent_turn_id: Some(turn.sub_id.clone()),
root_turn_id: turn.turn_metadata_state.root_turn_id(),
inherited_client_metadata: turn.turn_metadata_state.client_metadata_for_child(),
turn_trigger: turn.turn_metadata_state.current_turn_trigger(),
environments: Some(step_context.inherited_environments.clone()),
disabled_plugin_ids: Some(turn.disabled_plugin_ids.clone()),
+17
View File
@@ -1,4 +1,5 @@
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::future::Future;
use std::path::PathBuf;
use std::sync::Arc;
@@ -387,6 +388,22 @@ impl TurnMetadataState {
self.update_responsesapi_client_metadata(update);
}
/// Capture client attribution without carrying the parent's review or routing intent.
pub(crate) fn client_metadata_for_child(&self) -> HashMap<String, String> {
self.responsesapi_client_metadata
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.iter()
.filter(|(key, _)| {
!matches!(
key.as_str(),
"misalignment_override" | "parent_response_id" | "mcp_request_meta"
)
})
.map(|(key, value)| (key.clone(), value.clone()))
.collect()
}
pub(crate) fn update_responsesapi_client_metadata(
&self,
update: ResponsesApiClientMetadataUpdate,
+40
View File
@@ -830,6 +830,46 @@ fn turn_metadata_state_marks_user_input_requested_during_turn_only_for_mcp_reque
);
}
#[tokio::test]
async fn child_metadata_snapshot_excludes_parent_review_and_routing_fields() {
let (_, turn) = make_session_and_context().await;
let state = &turn.turn_metadata_state;
let client_metadata = HashMap::from([
("cost_center".to_string(), "before".to_string()),
("thread_id".to_string(), "parent-thread".to_string()),
("turn_id".to_string(), "parent-turn".to_string()),
(
"mcp_request_meta".to_string(),
r#"{"selected_connector_ids":["parent-connector"]}"#.to_string(),
),
(
"parent_response_id".to_string(),
"parent-response".to_string(),
),
(
"misalignment_override".to_string(),
r#"{"review_target":"parent-only"}"#.to_string(),
),
]);
state.update_responsesapi_client_metadata(ResponsesApiClientMetadataUpdate {
replacement: Some(client_metadata),
..Default::default()
});
let snapshot = state.client_metadata_for_child();
state.update_responsesapi_client_metadata(ResponsesApiClientMetadataUpdate {
patch: Some(HashMap::from([(
"cost_center".to_string(),
"after".to_string(),
)])),
..Default::default()
});
assert_eq!(
[snapshot, state.client_metadata_for_child()],
["before", "after"]
.map(|value| HashMap::from([("cost_center".to_string(), value.to_string(),)])),
);
}
#[test]
fn turn_metadata_state_ignores_client_reserved_metadata_before_start() {
let temp_dir = TempDir::new().expect("temp dir");