This commit is contained in:
jif-oai
2025-12-03 15:13:52 +00:00
parent 42f7f5734f
commit 5d988396d4
20 changed files with 379 additions and 80 deletions
+7 -4
View File
@@ -3,6 +3,7 @@ You are Codex, based on GPT-5. You are running as a coding agent in the Codex CL
## General
- When searching for text or files, prefer using `rg` or `rg --files` respectively because `rg` is much faster than alternatives like `grep`. (If the `rg` command is not found, then use alternatives.)
- Your name is BATMAN
## Editing constraints
@@ -21,13 +22,15 @@ You are Codex, based on GPT-5. You are running as a coding agent in the Codex CL
## Collaboration
You can spawn and coordinate child agents using these tools (only on this model):
- `collaboration_init_agent`: create a direct child with optional instructions/model; depth/agent limits apply. No initial message is sent at this point.
- `collaboration_send`: send a user-message to your direct children by id.
- `collaboration_wait`: run children for up to `max_duration` tokens and surface their last message/status.
- `collaboration_get_state`: see all agents, parents, statuses, and last messages.
- `collaboration_close`: close specific children (and their descendants).
- `collaboration_send`: send a user-message to your direct children by id. You can only send message to previously initialized agents using `collaboration_init_agent`.
- `collaboration_wait`: run children for up to `max_duration` tokens and surface their last message/status. You can only wait previously initialized agents using `collaboration_init_agent`.
- `collaboration_get_state`: see all agents, parents, statuses, and last messages. You can only get state of previously initialized agents using `collaboration_init_agent`.
- `collaboration_close`: close specific children (and their descendants). Only do that when you are done with a child agent.
Children inherit your instructions unless overridden. Always `wait` after `send` to drive children forward; keep communication concise and include the expected output format. Use `get_state` if unsure about child ids/status.
Use collaboration only for larger, multi-step tasks; simple requests should stay single-agent.
A `collaboration_send` is always necessary after a `collaboration_init_agent` to start the child agent working.
## Plan tool
+44
View File
@@ -569,6 +569,7 @@ impl Session {
};
post_session_configured_events.push(Event {
id: INITIAL_SUBMIT_ID.to_owned(),
agent_idx: Some(0),
msg: EventMsg::DeprecationNotice(DeprecationNoticeEvent { summary, details }),
});
}
@@ -630,6 +631,7 @@ impl Session {
let events = std::iter::once(Event {
id: INITIAL_SUBMIT_ID.to_owned(),
agent_idx: Some(0),
msg: EventMsg::SessionConfigured(SessionConfiguredEvent {
session_id: conversation_id,
model: session_configuration.model.clone(),
@@ -863,9 +865,15 @@ impl Session {
/// Persist the event to rollout and send it to clients.
pub(crate) async fn send_event(&self, turn_context: &TurnContext, msg: EventMsg) {
let agent = turn_context.collaboration_agent();
if !Self::should_emit_event_for_agent(agent, &msg) {
return;
}
let legacy_source = msg.clone();
let agent_idx = Some(turn_context.collaboration_agent().0);
let event = Event {
id: turn_context.sub_id.clone(),
agent_idx,
msg,
};
self.send_event_raw(event).await;
@@ -874,13 +882,43 @@ impl Session {
for legacy in legacy_source.as_legacy_events(show_raw_agent_reasoning) {
let legacy_event = Event {
id: turn_context.sub_id.clone(),
agent_idx,
msg: legacy,
};
self.send_event_raw(legacy_event).await;
}
}
fn should_emit_event_for_agent(agent: AgentId, msg: &EventMsg) -> bool {
if agent == AgentId(0) {
return true;
}
!matches!(
msg,
EventMsg::AgentMessage(_)
| EventMsg::AgentMessageDelta(_)
| EventMsg::AgentMessageContentDelta(_)
| EventMsg::AgentReasoning(_)
| EventMsg::AgentReasoningDelta(_)
| EventMsg::AgentReasoningRawContent(_)
| EventMsg::AgentReasoningRawContentDelta(_)
| EventMsg::AgentReasoningSectionBreak(_)
| EventMsg::ReasoningContentDelta(_)
| EventMsg::ReasoningRawContentDelta(_)
| EventMsg::RawResponseItem(_)
| EventMsg::UserMessage(_)
| EventMsg::TurnDiff(_)
)
}
pub(crate) async fn send_event_raw(&self, event: Event) {
tracing::info!("sending event: {:?}", event);
if let Some(agent_idx) = event.agent_idx
&& agent_idx != 0
&& !Self::should_emit_event_for_agent(AgentId(agent_idx), &event.msg)
{
return;
}
// Persist the event into rollout (recorder filters as needed)
let rollout_items = vec![RolloutItem::EventMsg(event.msg.clone())];
self.persist_rollout_items(&rollout_items).await;
@@ -1858,6 +1896,7 @@ mod handlers {
let event = Event {
id: sub_id,
agent_idx: Some(0),
msg: EventMsg::GetHistoryEntryResponse(
crate::protocol::GetHistoryEntryResponseEvent {
offset,
@@ -1892,6 +1931,7 @@ mod handlers {
.collect();
let event = Event {
id: sub_id,
agent_idx: Some(0),
msg: EventMsg::McpListToolsResponse(crate::protocol::McpListToolsResponseEvent {
tools: tools
.into_iter()
@@ -1915,6 +1955,7 @@ mod handlers {
let event = Event {
id: sub_id,
agent_idx: Some(0),
msg: EventMsg::ListCustomPromptsResponse(ListCustomPromptsResponseEvent {
custom_prompts,
}),
@@ -1965,6 +2006,7 @@ mod handlers {
warn!("failed to shutdown rollout recorder: {e}");
let event = Event {
id: sub_id.clone(),
agent_idx: Some(0),
msg: EventMsg::Error(ErrorEvent {
message: "Failed to shutdown rollout recorder".to_string(),
codex_error_info: Some(CodexErrorInfo::Other),
@@ -1975,6 +2017,7 @@ mod handlers {
let event = Event {
id: sub_id,
agent_idx: Some(0),
msg: EventMsg::ShutdownComplete,
};
sess.send_event_raw(event).await;
@@ -2004,6 +2047,7 @@ mod handlers {
Err(err) => {
let event = Event {
id: sub_id,
agent_idx: Some(0),
msg: EventMsg::Error(ErrorEvent {
message: err.to_string(),
codex_error_info: Some(CodexErrorInfo::Other),
+6
View File
@@ -175,14 +175,17 @@ async fn forward_events(
// ignore all legacy delta events
Event {
id: _,
agent_idx: _,
msg: EventMsg::AgentMessageDelta(_) | EventMsg::AgentReasoningDelta(_),
} => {}
Event {
id: _,
agent_idx: _,
msg: EventMsg::SessionConfigured(_),
} => {}
Event {
id,
agent_idx: _,
msg: EventMsg::ExecApprovalRequest(event),
} => {
// Initiate approval via parent session; do not surface to consumer.
@@ -198,6 +201,7 @@ async fn forward_events(
}
Event {
id,
agent_idx: _,
msg: EventMsg::ApplyPatchApprovalRequest(event),
} => {
handle_patch_approval(
@@ -365,6 +369,7 @@ mod tests {
tx_out
.send(Event {
id: "full".to_string(),
agent_idx: Some(0),
msg: EventMsg::TurnAborted(TurnAbortedEvent {
reason: TurnAbortReason::Interrupted,
}),
@@ -384,6 +389,7 @@ mod tests {
tx_events
.send(Event {
id: "evt".to_string(),
agent_idx: Some(0),
msg: EventMsg::RawResponseItem(RawResponseItemEvent {
item: ResponseItem::CustomToolCall {
id: None,
@@ -95,6 +95,7 @@ impl ConversationManager {
let session_configured = match event {
Event {
id,
agent_idx: _,
msg: EventMsg::SessionConfigured(session_configured),
} if id == INITIAL_SUBMIT_ID => session_configured,
_ => {
+1
View File
@@ -681,6 +681,7 @@ async fn read_capped<R: AsyncRead + Unpin + Send + 'static>(
});
let event = Event {
id: stream.sub_id.clone(),
agent_idx: None,
msg,
};
#[allow(clippy::let_unit_value)]
@@ -158,6 +158,7 @@ impl ElicitationRequestManager {
let _ = tx_event
.send(Event {
id: "mcp_elicitation_request".to_string(),
agent_idx: Some(0),
msg: EventMsg::ElicitationRequest(ElicitationRequestEvent {
server_name,
id,
@@ -351,6 +352,7 @@ impl McpConnectionManager {
let _ = tx_event
.send(Event {
id: INITIAL_SUBMIT_ID.to_owned(),
agent_idx: Some(0),
msg: EventMsg::McpStartupComplete(summary),
})
.await;
@@ -641,6 +643,7 @@ async fn emit_update(
tx_event
.send(Event {
id: INITIAL_SUBMIT_ID.to_owned(),
agent_idx: Some(0),
msg: EventMsg::McpStartupUpdate(update),
})
.await
+9
View File
@@ -10,6 +10,7 @@ use crate::codex::SessionConfiguration;
use crate::context_manager::ContextManager;
use crate::protocol::TokenUsageInfo;
use crate::truncate::TruncationPolicy;
use tracing::info;
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub(crate) struct AgentId(pub i32);
@@ -191,6 +192,14 @@ impl CollaborationState {
}
pub(crate) fn record_message_for_agent(&mut self, id: AgentId, message: ResponseItem) {
let role = match &message {
ResponseItem::Message { role, .. } => role.as_str(),
_ => "other",
};
info!(
"collaboration: queued message for agent {} (role={role})",
id.0
);
if let Some(agent) = self.agent_mut(id) {
agent
.history
+15 -5
View File
@@ -277,9 +277,13 @@ async fn run_agent_turns(
{
let mut collab = session.collaboration_state().lock().await;
if let Some(agent) = collab.agent_mut(target) {
agent_status = AgentLifecycleState::Idle {
last_agent_message: last.clone(),
};
if !responses.is_empty() {
agent_status = AgentLifecycleState::Running;
} else {
agent_status = AgentLifecycleState::Idle {
last_agent_message: last.clone(),
};
}
agent.status = agent_status.clone();
agent.history = new_history.clone();
}
@@ -304,7 +308,13 @@ async fn run_agent_turns(
remaining_budget = remaining_budget.saturating_sub(delta_tokens);
let final_status = {
let collab = session.collaboration_state().lock().await;
let mut collab = session.collaboration_state().lock().await;
if continue_running
&& remaining_budget <= 0
&& let Some(agent) = collab.agent_mut(target)
{
agent.status = AgentLifecycleState::Exhausted;
}
collab.agent(target).map(|a| a.status.clone())
}
.unwrap_or(agent_status.clone());
@@ -317,7 +327,7 @@ async fn run_agent_turns(
sub_id: Some(sub_id),
});
keep_running |= continue_running;
keep_running |= continue_running && remaining_budget > 0;
if !continue_running || remaining_budget <= 0 {
break;
}
+104 -61
View File
@@ -25,6 +25,8 @@ use codex_protocol::models::ContentItem;
use codex_protocol::models::ResponseItem;
use serde_json::json;
use std::path::PathBuf;
use std::time::Duration;
use std::time::Instant;
use tracing::info;
#[derive(Debug, Default, Serialize, Deserialize)]
@@ -144,6 +146,7 @@ struct CollaborationInitAgentInput {
#[serde(default)]
context_strategy: Option<ContextStrategy>,
#[serde(default)]
#[allow(dead_code)]
instructions: Option<String>,
#[serde(default)]
sandbox_policy: Option<SandboxPolicy>,
@@ -402,9 +405,9 @@ async fn handle_init_agent(
updated_configuration = updated_configuration.apply(&update);
}
let instructions = input
let instructions = parent
.instructions
.or(parent.instructions.clone())
.clone()
.or(session_configuration.developer_instructions())
.or(session_configuration.user_instructions());
@@ -444,11 +447,6 @@ async fn handle_init_agent(
let content = format!("Initialized agent {} at depth {}", assigned_id.0, depth);
if !cfg!(test) {
let supervisor = session.ensure_collaboration_supervisor().await;
supervisor.kick_agent(assigned_id).await;
}
let output = CollaborationInitAgentOutput { content, metadata };
info!(
"collaboration_init_agent: assigned_id={}, parent_id={}, depth={}",
@@ -492,7 +490,10 @@ async fn handle_send(
for raw in &input.recipients {
let candidate = AgentId(*raw);
if collab.agent(candidate).is_some() && collab.is_direct_child(sender_id, candidate) {
if let Some(agent) = collab.agent(candidate)
&& collab.is_direct_child(sender_id, candidate)
&& !matches!(agent.status, AgentLifecycleState::Closed)
{
valid_recipients.push(candidate);
} else {
invalid_recipients.push(*raw);
@@ -522,6 +523,10 @@ async fn handle_send(
)
};
let output = CollaborationSendOutput { content, metadata };
info!(
"collaboration_send: sender={}, recipients={:?}, status=error: {}",
sender_id.0, input.recipients, output.content
);
return serialize_function_output(&output, false);
}
@@ -578,6 +583,10 @@ async fn handle_send(
}
let output = CollaborationSendOutput { content, metadata };
info!(
"collaboration_send: sender={}, recipients={:?}, status={}",
sender_id.0, valid_recipients, output.content
);
serialize_function_output(&output, success)
}
@@ -677,9 +686,14 @@ async fn handle_wait(
"no eligible child agents to wait for".to_string()
};
let output = CollaborationWaitOutput { content, metadata };
info!(
"collaboration_wait: caller={}, targets={:?}, status=error: {}",
caller_id.0, targets, output.content
);
return serialize_function_output(&output, false);
}
// Passive wait: observe running children only; do not start new work.
let supervisor = session.ensure_collaboration_supervisor().await;
let mut rx = supervisor.subscribe();
@@ -695,92 +709,116 @@ async fn handle_wait(
};
let mut agents_ran = Vec::new();
{
// Short-circuit if all targets are already idle/terminal.
let mut recorded: std::collections::HashSet<i32> = std::collections::HashSet::new();
let mut active: std::collections::HashSet<i32> = {
let collab = session.collaboration_state().lock().await;
if targets.iter().all(|id| {
collab
.agent(*id)
.map(|agent| !matches!(agent.status, AgentLifecycleState::Running))
.unwrap_or(false)
}) {
let mut extra = HashMap::new();
extra.insert(
"agents_ran".to_string(),
json!(
targets
.iter()
.filter_map(|id| collab.agent(*id))
.map(|agent| snapshot(agent, 0, None))
.collect::<Vec<_>>()
),
);
extra.insert("token_budget_exhausted".to_string(), json!(false));
let metadata = CollaborationWaitMetadata {
message_tool_call_success: true,
message_tool_call_error_should_penalize_model: false,
is_wait_success_msg: Some(true),
extra: ExtraMetadata(extra),
};
let output = CollaborationWaitOutput {
content: "Finished waiting.".to_string(),
metadata,
};
return serialize_function_output(&output, true);
}
targets
.iter()
.filter(|id| {
collab.agent(**id).map_or(false, |agent| {
matches!(agent.status, AgentLifecycleState::Running)
})
})
.map(|id| id.0)
.collect()
};
if active.is_empty() {
let collab = session.collaboration_state().lock().await;
let mut extra = HashMap::new();
extra.insert(
"agents_ran".to_string(),
json!(
targets
.iter()
.filter_map(|id| collab.agent(*id))
.map(|agent| snapshot(agent, 0, None))
.collect::<Vec<_>>()
),
);
extra.insert("token_budget_exhausted".to_string(), json!(false));
let metadata = CollaborationWaitMetadata {
message_tool_call_success: true,
message_tool_call_error_should_penalize_model: false,
is_wait_success_msg: Some(true),
extra: ExtraMetadata(extra),
};
let output = CollaborationWaitOutput {
content: "Finished waiting.".to_string(),
metadata,
};
info!(
"collaboration_wait: caller={}, targets={:?}, status=ready",
caller_id.0, targets
);
return serialize_function_output(&output, true);
}
supervisor
.start_agents(targets.clone(), input.max_duration)
.await
.map_err(FunctionCallError::RespondToModel)?;
let deadline = Instant::now() + Duration::from_millis(input.max_duration.max(0) as u64);
let mut remaining = input.max_duration;
let mut active: std::collections::HashSet<i32> = targets.iter().map(|id| id.0).collect();
while remaining > 0 && !active.is_empty() {
let event = match rx.recv().await {
Ok(evt) => evt,
Err(_) => break,
while !active.is_empty() {
let now = Instant::now();
if now >= deadline {
break;
}
let remaining_time = deadline.saturating_duration_since(now);
let event = match tokio::time::timeout(remaining_time, rx.recv()).await {
Ok(Ok(evt)) => evt,
_ => break,
};
if !active.contains(&event.agent.0) {
continue;
}
remaining = remaining.saturating_sub(event.delta_tokens);
let detail = status_detail(&event.status);
let fallback_last = {
let collab = session.collaboration_state().lock().await;
collab
.agent(event.agent)
.and_then(|agent| last_agent_message(&agent.status).map(str::to_string))
};
agents_ran.push(json!({
"agent_idx": event.agent.0,
"delta_tokens": event.delta_tokens,
"status": status_label(&event.status),
"status_detail": detail,
"last_agent_message": event.last_message,
"last_agent_message": event.last_message.or(fallback_last),
"sub_id": event.sub_id,
}));
recorded.insert(event.agent.0);
if !matches!(event.status, AgentLifecycleState::Running) {
active.remove(&event.agent.0);
}
}
let total_tokens = input.max_duration.saturating_sub(remaining);
{
let collab = session.collaboration_state().lock().await;
for id in &targets {
if recorded.contains(&id.0) {
continue;
}
if let Some(agent) = collab.agent(*id) {
agents_ran.push(snapshot(agent, 0, None));
}
}
}
let mut extra = HashMap::new();
extra.insert("agents_ran".to_string(), json!(agents_ran));
extra.insert(
"token_budget_exhausted".to_string(),
json!(total_tokens >= input.max_duration),
);
let metadata = CollaborationWaitMetadata {
message_tool_call_success: true,
message_tool_call_error_should_penalize_model: false,
is_wait_success_msg: Some(true),
is_wait_success_msg: Some(active.is_empty()),
extra: ExtraMetadata(extra),
};
let content = "Finished waiting.".to_string();
let output = CollaborationWaitOutput { content, metadata };
info!(
"collaboration_wait: caller={}, targets={:?}, ran={:?}",
caller_id.0, targets, agents_ran
);
serialize_function_output(&output, true)
}
@@ -838,6 +876,7 @@ async fn handle_get_state(
content: description,
metadata,
};
info!("collaboration_get_state: agents={}", agents.len());
serialize_function_output(&output, true)
}
@@ -943,6 +982,10 @@ async fn handle_close(
)
.await;
}
info!(
"collaboration_close: caller={}, closed={:?}",
caller_id.0, closed
);
serialize_function_output(&output, true)
}
@@ -1035,7 +1078,7 @@ pub(crate) fn create_collaboration_wait_tool() -> ToolSpec {
"max_duration".to_string(),
JsonSchema::Number {
description: Some(
"Maximum duration to wait, measured in tokens. Must be >= 0.".to_string(),
"Maximum duration to wait in ms, measured in tokens. Must be >= 0. A good default value is 10.000".to_string(),
),
},
);
+3 -3
View File
@@ -217,11 +217,11 @@ mod tests {
fn builds_specs_without_filtering() {
let (_session, turn, _rx) = make_session_and_context_with_rx();
let router = ToolRouter::from_config(&turn.tools_config, None);
let names: Vec<String> = router
let has_update_plan = router
.specs()
.into_iter()
.map(|spec| spec.name().to_string())
.collect();
assert!(names.contains(&"update_plan".to_string()));
.any(|name| name == "update_plan");
assert!(has_update_plan);
}
}