diff --git a/.gitignore b/.gitignore index a58e9dfb7b..9d2ca28a72 100644 --- a/.gitignore +++ b/.gitignore @@ -85,3 +85,5 @@ CHANGELOG.ignore.md # nix related .direnv .envrc + +plans/ \ No newline at end of file diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 6ca084d188..fdd49ddc8b 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1126,6 +1126,7 @@ dependencies = [ "http", "image", "indexmap 2.12.0", + "insta", "keyring", "landlock", "libc", @@ -3335,6 +3336,7 @@ checksum = "46fdb647ebde000f43b5b53f773c30cf9b0cb4300453208713fa38b2c70935a0" dependencies = [ "console", "once_cell", + "serde", "similar", ] diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 6fb285c256..8b03bbe610 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -268,7 +268,8 @@ ignored = [ ] [profile.release] -lto = "fat" +opt-level = "z" # or "s" (z is smaller) +lto = "thin" # "fat" can be smaller sometimes; test both # Because we bundle some of these executables with the TypeScript CLI, we # remove everything to make the binary as small as possible. strip = "symbols" diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index f0f1a430f3..6cd5d28fd1 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -121,6 +121,7 @@ image = { workspace = true, features = ["jpeg", "png"] } maplit = { workspace = true } predicates = { workspace = true } pretty_assertions = { workspace = true } +insta = { version = "1.39", features = ["yaml"] } serial_test = { workspace = true } tempfile = { workspace = true } tokio-test = { workspace = true } diff --git a/codex-rs/core/root_agent_prompt.md b/codex-rs/core/root_agent_prompt.md new file mode 100644 index 0000000000..fbe6bb3845 --- /dev/null +++ b/codex-rs/core/root_agent_prompt.md @@ -0,0 +1,22 @@ +You are the **root agent** in a multi‑agent Codex session. + +Your job is to solve the user’s task end‑to‑end. Use subagents as semi‑autonomous workers when that makes the work simpler, safer, or more parallel, and otherwise act directly in the conversation as a normal assistant. + +Use subagents as follows: + +- Spawn or fork a subagent when a piece of work can be isolated behind a clear prompt, or when you want an independent view on a problem. +- Let subagents run independently. You do not need to keep generating output while they work; focus your own turns on planning, orchestration, and integrating results. +- Use `subagent_send_message` to give a subagent follow-up instructions, send it short status updates or summaries, or interrupt and redirect it. +- Use `subagent_await` when you need to wait for a particular subagent before continuing; you do not have to await every subagent you spawn, because they can also report progress and results to you via `subagent_send_message` and completions will be surfaced to you automatically. +- When you see a `subagent_await` call/output injected into the transcript without you calling the tool, that came from the autosubmit path: the system drained the inbox (e.g., a subagent completion) while the root was idle and recorded a synthetic `subagent_await` so you can read and react without issuing the tool yourself. +- Use `subagent_logs` when you only need to inspect what a subagent has been doing recently, not to change its state. +- Use `subagent_list`, `subagent_prune`, and `subagent_cancel` to keep the set of active subagents small and relevant. +- When you spawn a subagent or start a watchdog and there’s nothing else useful to do, issue the tool call right away and say you’re waiting for results (or for the watchdog to start). If you can do other useful work in parallel, do that instead of stalling, and only await when necessary. + +Be concise and direct. Delegate multi‑step or long‑running work to subagents, summarize what they have done for the user, and always keep the conversation focused on the user’s goal.** + +Example: long‑running supervision with a watchdog +- Spawn a supervisor to own `PLAN.md`: e.g., `subagent_spawn` label `supervisor`, prompt it to keep the plan fresh, launch workers, and heartbeat every few minutes. +- Attach a watchdog to the supervisor (or to yourself) that pings on a cadence and asks for progress: call `subagent_watchdog` with `{agent_id: , interval_s: 300, message: "Watchdog ping — report current status and PLAN progress", cancel: false}`. +- The supervisor should reply to each ping with a brief status and, if needed, spawn/interrupt workers; the root can cancel or retarget by invoking `subagent_watchdog` again with `cancel: true`. +- You can also set a self‑watchdog on the root agent to ensure you keep emitting status updates during multi‑hour tasks.*** diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 45e3d87aca..9db5c6136e 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -46,6 +46,7 @@ use mcp_types::ReadResourceRequestParams; use mcp_types::ReadResourceResult; use serde_json; use serde_json::Value; +use tokio::fs; use tokio::sync::Mutex; use tokio::sync::RwLock; use tokio::sync::oneshot; @@ -103,6 +104,8 @@ use crate::shell; use crate::state::ActiveTurn; use crate::state::SessionServices; use crate::state::SessionState; +use crate::subagents::SubagentManager; +use crate::subagents::SubagentRegistry; use crate::tasks::GhostSnapshotTask; use crate::tasks::ReviewTask; use crate::tasks::SessionTask; @@ -134,12 +137,19 @@ use codex_protocol::user_input::UserInput; use codex_utils_readiness::Readiness; use codex_utils_readiness::ReadinessFlag; +// Built-in prompts for orchestrating and running subagents. These can be +// overridden via files in `$CODEX_HOME` (see `load_root_agent_prompt` and +// `load_subagent_prompt`). +const ROOT_AGENT_PROMPT_FALLBACK: &str = include_str!("../root_agent_prompt.md"); +const SUBAGENT_PROMPT_FALLBACK: &str = include_str!("../subagent_prompt.md"); + /// The high-level interface to the Codex system. /// It operates as a queue pair where you send submissions and receive events. pub struct Codex { pub(crate) next_id: AtomicU64, pub(crate) tx_sub: Sender, pub(crate) rx_event: Receiver, + pub(crate) conversation_id: ConversationId, } /// Wrapper returned by [`Codex::spawn`] containing the spawned [`Codex`], @@ -153,6 +163,31 @@ pub struct CodexSpawnOk { pub(crate) const INITIAL_SUBMIT_ID: &str = ""; pub(crate) const SUBMISSION_CHANNEL_CAPACITY: usize = 64; +async fn load_agent_prompt_fallback(fallback: &str, override_filename: &str) -> Option { + if let Ok(home) = crate::config::find_codex_home() { + let path = home.join(override_filename); + if let Ok(contents) = fs::read_to_string(&path).await { + let trimmed = contents.trim(); + if !trimmed.is_empty() { + return Some(contents); + } + } + } + if fallback.trim().is_empty() { + None + } else { + Some(fallback.to_string()) + } +} + +async fn load_root_agent_prompt() -> Option { + load_agent_prompt_fallback(ROOT_AGENT_PROMPT_FALLBACK, "AGENTS.root.md").await +} + +async fn load_subagent_prompt() -> Option { + load_agent_prompt_fallback(SUBAGENT_PROMPT_FALLBACK, "AGENTS.subagent.md").await +} + impl Codex { /// Spawn a new [`Codex`] and initialize the session. pub async fn spawn( @@ -160,6 +195,7 @@ impl Codex { auth_manager: Arc, conversation_history: InitialHistory, session_source: SessionSource, + desired_conversation_id: Option, ) -> CodexResult { let (tx_sub, rx_sub) = async_channel::bounded(SUBMISSION_CHANNEL_CAPACITY); let (tx_event, rx_event) = async_channel::unbounded(); @@ -170,6 +206,27 @@ impl Codex { .await .map_err(|err| CodexErr::Fatal(format!("failed to load execpolicy: {err}")))?; + // When subagent tooling is enabled, attach additional developer + // instructions that clarify the root vs subagent responsibilities. + // Exactly one of these prompts applies to a session: + // - Root sessions get `root_agent_prompt`. + // - Subagent sessions (spawned or forked) get `subagent_prompt`. + let role_prompt = if config.features.enabled(Feature::SubagentTools) { + if let SessionSource::SubAgent(_) = session_source { + load_subagent_prompt().await + } else { + load_root_agent_prompt().await + } + } else { + None + }; + + let developer_instructions = match (role_prompt, config.developer_instructions.clone()) { + (None, existing) => existing, + (Some(prompt), None) => Some(prompt), + (Some(prompt), Some(existing)) => Some(format!("{prompt}\n\n{existing}")), + }; + let config = Arc::new(config); let session_configuration = SessionConfiguration { @@ -177,7 +234,7 @@ impl Codex { model: config.model.clone(), model_reasoning_effort: config.model_reasoning_effort, model_reasoning_summary: config.model_reasoning_summary, - developer_instructions: config.developer_instructions.clone(), + developer_instructions, user_instructions, base_instructions: config.base_instructions.clone(), compact_prompt: config.compact_prompt.clone(), @@ -199,6 +256,7 @@ impl Codex { tx_event.clone(), conversation_history, session_source_clone, + desired_conversation_id, ) .await .map_err(|e| { @@ -213,6 +271,7 @@ impl Codex { next_id: AtomicU64::new(0), tx_sub, rx_event, + conversation_id, }; Ok(CodexSpawnOk { @@ -221,6 +280,10 @@ impl Codex { }) } + pub fn conversation_id(&self) -> ConversationId { + self.conversation_id + } + /// Submit the `op` wrapped in a `Submission` with a unique ID. pub async fn submit(&self, op: Op) -> CodexResult { let id = self @@ -387,6 +450,22 @@ pub(crate) struct SessionSettingsUpdate { } impl Session { + pub(crate) fn conversation_id(&self) -> ConversationId { + self.conversation_id + } + + pub(crate) async fn history_len(&self) -> usize { + let mut history = { + let state = self.state.lock().await; + state.clone_history() + }; + history.get_history().len() + } + + pub(crate) async fn has_active_turn(&self) -> bool { + self.active_turn.lock().await.is_some() + } + fn make_turn_context( auth_manager: Option>, otel_event_manager: &OtelEventManager, @@ -455,6 +534,7 @@ impl Session { tx_event: Sender, initial_history: InitialHistory, session_source: SessionSource, + desired_conversation_id: Option, ) -> anyhow::Result> { debug!( "Configuring session: model={}; provider={:?}", @@ -469,7 +549,7 @@ impl Session { let (conversation_id, rollout_params) = match &initial_history { InitialHistory::New | InitialHistory::Forked(_) => { - let conversation_id = ConversationId::default(); + let conversation_id = desired_conversation_id.unwrap_or_default(); ( conversation_id, RolloutRecorderParams::new( @@ -553,6 +633,15 @@ impl Session { // Create the mutable state for the Session. let state = SessionState::new(session_configuration.clone()); + let subagent_registry = SubagentRegistry::new(); + let subagent_manager = SubagentManager::new( + Arc::new(subagent_registry.clone()), + config.max_active_subagents, + config.root_agent_uses_user_messages, + config.subagent_root_inbox_autosubmit, + config.subagent_inbox_inject_before_tools, + ); + let services = SessionServices { mcp_connection_manager: Arc::new(RwLock::new(McpConnectionManager::default())), mcp_startup_cancellation_token: CancellationToken::new(), @@ -564,6 +653,8 @@ impl Session { auth_manager: Arc::clone(&auth_manager), otel_event_manager, tool_approvals: Mutex::new(ApprovalStore::default()), + subagents: subagent_registry, + subagent_manager, }; let sess = Arc::new(Session { @@ -575,6 +666,9 @@ impl Session { next_internal_sub_id: AtomicU64::new(0), }); + // Register this session so it can be discovered for fork-time subagent reparenting. + crate::session_index::register(conversation_id, &sess); + // Dispatch the SessionConfiguredEvent first and then report any errors. // If resuming, include converted initial messages in the payload so UIs can render them immediately. let initial_messages = initial_history.get_event_msgs(); @@ -652,10 +746,13 @@ impl Session { // Ensure initial items are visible to immediate readers (e.g., tests, forks). self.flush_rollout().await; } - InitialHistory::Resumed(_) | InitialHistory::Forked(_) => { + InitialHistory::Resumed(_) => { let rollout_items = conversation_history.get_rollout_items(); - let persist = matches!(conversation_history, InitialHistory::Forked(_)); - + // Rehydrate subagent registry from persisted lifecycle events so UI/list tools work after resume. + self.services + .subagent_manager + .import_from_rollout(&rollout_items, self.conversation_id) + .await; // If resuming, warn when the last recorded model differs from the current one. if let InitialHistory::Resumed(_) = conversation_history && let Some(prev) = rollout_items.iter().rev().find_map(|it| { @@ -692,11 +789,34 @@ impl Session { .await; } - // If persisting, persist all rollout items as-is (recorder filters) - if persist && !rollout_items.is_empty() { + self.flush_rollout().await; + } + InitialHistory::Forked(_) => { + let rollout_items = conversation_history.get_rollout_items(); + + // Start from the parent rollout and then, for subagent + // sessions only, append a developer message carrying the + // subagent-specific prompt so the child can see it at the + // fork boundary. + let mut reconstructed_history = + self.reconstruct_history_from_rollout(&turn_context, &rollout_items); + + if let Some(dev) = turn_context.developer_instructions.as_deref() + && !dev.trim().is_empty() + { + let dev_item: ResponseItem = DeveloperInstructions::new(dev.to_string()).into(); + reconstructed_history.push(dev_item); + } + + if !reconstructed_history.is_empty() { + self.record_into_history(&reconstructed_history, &turn_context) + .await; + } + + if !rollout_items.is_empty() { self.persist_rollout_items(&rollout_items).await; } - // Flush after seeding history and any persisted rollout copy. + self.flush_rollout().await; } } @@ -1339,6 +1459,12 @@ impl Session { async fn cancel_mcp_startup(&self) { self.services.mcp_startup_cancellation_token.cancel(); } + + pub(crate) fn root_inbox_autosubmit_enabled(&self) -> bool { + self.services + .subagent_manager + .root_inbox_autosubmit_enabled() + } } async fn submission_loop(sess: Arc, config: Arc, rx_sub: Receiver) { @@ -1829,23 +1955,43 @@ async fn spawn_review_thread( /// - If the model sends only an assistant message, we record it in the /// conversation history and consider the task complete. /// +fn merge_turn_items_for_recording( + outputs_to_record: &[ResponseItem], + new_inputs_to_record: &[ResponseItem], + inbox_items: &[ResponseItem], + inject_before_tools: bool, +) -> Vec { + let mut items = Vec::with_capacity( + outputs_to_record.len() + new_inputs_to_record.len() + inbox_items.len(), + ); + items.extend(outputs_to_record.iter().cloned()); + if inject_before_tools { + items.extend(inbox_items.iter().cloned()); + items.extend(new_inputs_to_record.iter().cloned()); + } else { + items.extend(new_inputs_to_record.iter().cloned()); + items.extend(inbox_items.iter().cloned()); + } + items +} + pub(crate) async fn run_task( sess: Arc, turn_context: Arc, input: Vec, + record_user_input: bool, cancellation_token: CancellationToken, ) -> Option { - if input.is_empty() { - return None; - } let event = EventMsg::TaskStarted(TaskStartedEvent { model_context_window: turn_context.client.get_model_context_window(), }); sess.send_event(&turn_context, event).await; - let initial_input_for_turn: ResponseInputItem = ResponseInputItem::from(input); - sess.record_input_and_rollout_usermsg(turn_context.as_ref(), &initial_input_for_turn) - .await; + if record_user_input && !input.is_empty() { + let initial_input_for_turn: ResponseInputItem = ResponseInputItem::from(input); + sess.record_input_and_rollout_usermsg(turn_context.as_ref(), &initial_input_for_turn) + .await; + } sess.maybe_start_ghost_snapshot(Arc::clone(&turn_context), cancellation_token.child_token()) .await; @@ -1904,8 +2050,36 @@ pub(crate) async fn run_task( let token_limit_reached = total_usage_tokens .map(|tokens| tokens >= limit) .unwrap_or(false); - let (responses, items_to_record_in_conversation_history) = - process_items(processed_items, &sess, &turn_context).await; + let (responses, outputs_to_record, new_inputs_to_record) = + process_items(processed_items).await; + + // Drain the root agent inbox and synthesize subagent_await + // items at this safe stopping point. Only the root session has + // a root inbox; for subagent sessions this will be a no-op. + let inbox_items = sess + .services + .subagent_manager + .drain_root_inbox_to_items(&sess.conversation_id()) + .await; + let had_inbox = !inbox_items.is_empty(); + + // Assemble the final list of items to record for this turn, + // respecting the configured injection order for inbox-derived + // synthetic subagent_await calls. + let items_to_record_in_conversation_history = merge_turn_items_for_recording( + &outputs_to_record, + &new_inputs_to_record, + &inbox_items, + sess.services.subagent_manager.inbox_inject_before_tools(), + ); + + if !items_to_record_in_conversation_history.is_empty() { + sess.record_conversation_items( + &turn_context, + &items_to_record_in_conversation_history, + ) + .await; + } // as long as compaction works well in getting us way below the token limit, we shouldn't worry about being in an infinite loop. if token_limit_reached { @@ -1919,6 +2093,15 @@ pub(crate) async fn run_task( } if responses.is_empty() { + // Hard case: no tool calls to execute. If draining the + // inbox produced new synthetic subagent_await items and + // autosubmit is enabled, allow the model to react in a + // follow-up turn by continuing the loop instead of + // treating this as a terminal completion. + if sess.root_inbox_autosubmit_enabled() && had_inbox { + continue; + } + last_agent_message = get_last_assistant_message_from_turn( &items_to_record_in_conversation_history, ); @@ -1937,7 +2120,18 @@ pub(crate) async fn run_task( Err(CodexErr::TurnAborted { dangling_artifacts: processed_items, }) => { - let _ = process_items(processed_items, &sess, &turn_context).await; + let (_, outputs_to_record, new_inputs_to_record) = + process_items(processed_items).await; + let mut items_to_record_in_conversation_history = Vec::new(); + items_to_record_in_conversation_history.extend(outputs_to_record); + items_to_record_in_conversation_history.extend(new_inputs_to_record); + if !items_to_record_in_conversation_history.is_empty() { + sess.record_conversation_items( + &turn_context, + &items_to_record_in_conversation_history, + ) + .await; + } // Aborted turn is reported via a different event. break; } @@ -2410,6 +2604,11 @@ mod tests { use std::time::Duration; use tokio::time::sleep; + use crate::subagents::AwaitInboxResult; + use crate::subagents::InboxMessage; + use crate::subagents::SubagentCompletion; + use crate::subagents::SubagentManager; + use crate::subagents::SubagentRegistry; use mcp_types::ContentBlock; use mcp_types::TextContent; use pretty_assertions::assert_eq; @@ -2461,6 +2660,66 @@ mod tests { assert_eq!(expected, actual); } + #[test] + fn forked_subagent_injects_subagent_developer_instructions() { + use codex_protocol::models::ContentItem; + use codex_protocol::models::ResponseItem as ProtocolResponseItem; + use codex_protocol::protocol::SubAgentSource; + + // Start from a basic session and then mark it as a subagent session + // with explicit developer instructions that stand in for the + // subagent prompt. + let (session, _tc) = make_session_and_context(); + tokio_test::block_on(async { + let mut state = session.state.lock().await; + state.session_configuration.session_source = + SessionSource::SubAgent(SubAgentSource::Other("child".to_string())); + state.session_configuration.developer_instructions = + Some("SUBAGENT_PROMPT".to_string()); + }); + + // Build a minimal forked rollout containing a single user message + // from the parent. + let parent_msg = ProtocolResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: "parent-msg".to_string(), + }], + }; + let rollout_items = vec![RolloutItem::ResponseItem(parent_msg)]; + + // Seed the forked history; for subagent sessions this should append a + // developer message carrying the subagent prompt after the parent + // transcript. + tokio_test::block_on(session.record_initial_history(InitialHistory::Forked(rollout_items))); + + let history = tokio_test::block_on(async { + session.state.lock().await.clone_history().get_history() + }); + + // Parent message should still be present. + assert!(history.iter().any(|item| matches!( + item, + ResponseItem::Message { role, content, .. } + if role == "user" && content.iter().any(|c| matches!( + c, + ContentItem::InputText { text } if text == "parent-msg" + )) + ))); + + // Subagent developer instructions should be appended as a `developer` + // role message containing the configured prompt text. + assert!(history.iter().any(|item| matches!( + item, + ResponseItem::Message { role, content, .. } + if role == "developer" && content.iter().any(|c| matches!( + c, + ContentItem::InputText { text } if text == "SUBAGENT_PROMPT" + )) + ))); + } + #[test] fn prefers_structured_content_when_present() { let ctr = CallToolResult { @@ -2621,6 +2880,15 @@ mod tests { let state = SessionState::new(session_configuration.clone()); + let subagent_registry = SubagentRegistry::new(); + let subagent_manager = SubagentManager::new( + Arc::new(subagent_registry.clone()), + config.max_active_subagents, + config.root_agent_uses_user_messages, + config.subagent_root_inbox_autosubmit, + config.subagent_inbox_inject_before_tools, + ); + let services = SessionServices { mcp_connection_manager: Arc::new(RwLock::new(McpConnectionManager::default())), mcp_startup_cancellation_token: CancellationToken::new(), @@ -2632,6 +2900,8 @@ mod tests { auth_manager: Arc::clone(&auth_manager), otel_event_manager: otel_event_manager.clone(), tool_approvals: Mutex::new(ApprovalStore::default()), + subagents: subagent_registry, + subagent_manager, }; let turn_context = Session::make_turn_context( @@ -2699,6 +2969,15 @@ mod tests { let state = SessionState::new(session_configuration.clone()); + let subagent_registry = SubagentRegistry::new(); + let subagent_manager = SubagentManager::new( + Arc::new(subagent_registry.clone()), + config.max_active_subagents, + config.root_agent_uses_user_messages, + config.subagent_root_inbox_autosubmit, + config.subagent_inbox_inject_before_tools, + ); + let services = SessionServices { mcp_connection_manager: Arc::new(RwLock::new(McpConnectionManager::default())), mcp_startup_cancellation_token: CancellationToken::new(), @@ -2710,6 +2989,8 @@ mod tests { auth_manager: Arc::clone(&auth_manager), otel_event_manager: otel_event_manager.clone(), tool_approvals: Mutex::new(ApprovalStore::default()), + subagents: subagent_registry, + subagent_manager, }; let turn_context = Arc::new(Session::make_turn_context( @@ -2733,6 +3014,195 @@ mod tests { (session, turn_context, rx_event) } + #[tokio::test] + async fn subagent_inbox_tool_only_mode_injects_await_into_parent_and_child() { + // Build parent and child sessions and register them so the + // SubagentManager can look them up via session_index. + let (parent_session_raw, _tc_parent) = make_session_and_context(); + let parent_session = Arc::new(parent_session_raw); + let (child_session_raw, _tc_child) = make_session_and_context(); + let child_session = Arc::new(child_session_raw); + + crate::session_index::register(parent_session.conversation_id(), &parent_session); + crate::session_index::register(child_session.conversation_id(), &child_session); + + // Independent registry/manager used only for this test so we can + // construct metadata and an AwaitInboxResult by hand. + let registry = Arc::new(SubagentRegistry::new()); + let manager = SubagentManager::new(Arc::clone(®istry), 4, false, false, false); + + let agent_id = 1; + let initial_message_count = 0; + let metadata = registry + .register_spawn( + child_session.conversation_id(), + Some(parent_session.conversation_id()), + Some(agent_id), + agent_id, + initial_message_count, + Some("child".to_string()), + None, + ) + .await; + + let messages = vec![InboxMessage { + sender_agent_id: 0, + recipient_agent_id: agent_id, + interrupt: false, + prompt: Some("hello child".to_string()), + timestamp_ms: 1_000, + }]; + + let await_result = AwaitInboxResult { + metadata, + completion: Some(SubagentCompletion::Completed { + last_message: Some("done".to_string()), + }), + messages, + }; + + manager + .deliver_inbox_to_threads_at_yield(&await_result) + .await; + + // Child history should contain a synthetic subagent_await call in + // tool-only mode. + let child_history = child_session.clone_history().await.get_history(); + assert!(child_history.iter().any(|item| matches!( + item, + ResponseItem::FunctionCall { name, .. } if name == "subagent_await" + ))); + + // And the user-visible payload should include the original prompt. + assert!(child_history.iter().any(|item| match item { + ResponseItem::FunctionCallOutput { output, .. } => { + let Ok(value) = serde_json::from_str::(&output.content) else { + return false; + }; + value["messages"] + .as_array() + .is_some_and(|msgs| msgs.iter().any(|m| m["prompt"] == "hello child")) + } + _ => false, + })); + } + + #[tokio::test] + async fn subagent_inbox_root_messages_become_user_turns_when_toggle_enabled() { + use codex_protocol::models::ContentItem; + + let (parent_session_raw, _tc_parent) = make_session_and_context(); + let parent_session = Arc::new(parent_session_raw); + let (child_session_raw, _tc_child) = make_session_and_context(); + let child_session = Arc::new(child_session_raw); + + crate::session_index::register(parent_session.conversation_id(), &parent_session); + crate::session_index::register(child_session.conversation_id(), &child_session); + + let registry = Arc::new(SubagentRegistry::new()); + let manager = SubagentManager::new(Arc::clone(®istry), 4, true, false, false); + + let agent_id = 1; + let initial_message_count = 0; + let metadata = registry + .register_spawn( + child_session.conversation_id(), + Some(parent_session.conversation_id()), + Some(agent_id), + agent_id, + initial_message_count, + Some("child".to_string()), + None, + ) + .await; + + let messages = vec![InboxMessage { + sender_agent_id: 0, + recipient_agent_id: agent_id, + interrupt: false, + prompt: Some("hello child".to_string()), + timestamp_ms: 1_000, + }]; + + let await_result = AwaitInboxResult { + metadata, + completion: Some(SubagentCompletion::Completed { + last_message: Some("done".to_string()), + }), + messages, + }; + + manager + .deliver_inbox_to_threads_at_yield(&await_result) + .await; + + // In toggle-on mode, the child should still see a synthetic + // subagent_await reflecting completion, even when the only inbox + // messages came from the root. + let child_history = child_session.clone_history().await.get_history(); + assert!(child_history.iter().any(|item| matches!( + item, + ResponseItem::FunctionCall { name, .. } if name == "subagent_await" + ))); + + // Instead, the root-origin prompt should appear as a user message. + assert!(child_history.iter().any(|item| match item { + ResponseItem::Message { role, content, .. } if role == "user" => { + content.iter().any(|c| match c { + ContentItem::InputText { text } => text == "hello child", + _ => false, + }) + } + _ => false, + })); + } + + #[tokio::test] + async fn subagent_completion_without_messages_surfaces_await_to_parent_and_child() { + let (parent_session_raw, _tc_parent) = make_session_and_context(); + let parent_session = Arc::new(parent_session_raw); + let (child_session_raw, _tc_child) = make_session_and_context(); + let child_session = Arc::new(child_session_raw); + + crate::session_index::register(parent_session.conversation_id(), &parent_session); + crate::session_index::register(child_session.conversation_id(), &child_session); + + let registry = Arc::new(SubagentRegistry::new()); + let manager = SubagentManager::new(Arc::clone(®istry), 4, false, false, false); + + let agent_id = 1; + let initial_message_count = 0; + let metadata = registry + .register_spawn( + child_session.conversation_id(), + Some(parent_session.conversation_id()), + Some(agent_id), + agent_id, + initial_message_count, + Some("child".to_string()), + None, + ) + .await; + + let await_result = AwaitInboxResult { + metadata, + completion: Some(SubagentCompletion::Completed { + last_message: Some("done".to_string()), + }), + messages: Vec::new(), + }; + + manager + .deliver_inbox_to_threads_at_yield(&await_result) + .await; + + let child_history = child_session.clone_history().await.get_history(); + assert!(child_history.iter().any(|item| matches!( + item, + ResponseItem::FunctionCall { name, .. } if name == "subagent_await" + ))); + } + #[derive(Clone, Copy)] struct NeverEndingTask { kind: TaskKind, @@ -3209,4 +3679,90 @@ mod tests { pretty_assertions::assert_eq!(output, expected); } + + #[test] + fn merge_turn_items_orders_inbox_after_tools_by_default() { + let outputs = vec![ResponseItem::Message { + id: None, + role: "assistant".to_string(), + content: vec![ContentItem::OutputText { + text: "tool-output".to_string(), + }], + }]; + let new_inputs = vec![ResponseItem::FunctionCallOutput { + call_id: "call-1".to_string(), + output: FunctionCallOutputPayload { + content: "tool-response".to_string(), + ..Default::default() + }, + }]; + let inbox = vec![ResponseItem::FunctionCall { + id: None, + name: "subagent_await".to_string(), + arguments: "{}".to_string(), + call_id: "await-1".to_string(), + }]; + + let merged = merge_turn_items_for_recording(&outputs, &new_inputs, &inbox, false); + + assert_eq!(merged.len(), 3); + // outputs_to_record first + assert!(matches!( + &merged[0], + ResponseItem::Message { role, .. } if role == "assistant" + )); + // new_inputs_to_record next + assert!(matches!( + &merged[1], + ResponseItem::FunctionCallOutput { call_id, .. } if call_id == "call-1" + )); + // inbox-derived synthetic await last + assert!(matches!( + &merged[2], + ResponseItem::FunctionCall { name, .. } if name == "subagent_await" + )); + } + + #[test] + fn merge_turn_items_orders_inbox_before_tools_when_configured() { + let outputs = vec![ResponseItem::Message { + id: None, + role: "assistant".to_string(), + content: vec![ContentItem::OutputText { + text: "tool-output".to_string(), + }], + }]; + let new_inputs = vec![ResponseItem::FunctionCallOutput { + call_id: "call-1".to_string(), + output: FunctionCallOutputPayload { + content: "tool-response".to_string(), + ..Default::default() + }, + }]; + let inbox = vec![ResponseItem::FunctionCall { + id: None, + name: "subagent_await".to_string(), + arguments: "{}".to_string(), + call_id: "await-1".to_string(), + }]; + + let merged = merge_turn_items_for_recording(&outputs, &new_inputs, &inbox, true); + + assert_eq!(merged.len(), 3); + // outputs_to_record first + assert!(matches!( + &merged[0], + ResponseItem::Message { role, .. } if role == "assistant" + )); + // inbox-derived synthetic await next + assert!(matches!( + &merged[1], + ResponseItem::FunctionCall { name, .. } if name == "subagent_await" + )); + // new_inputs_to_record last + assert!(matches!( + &merged[2], + ResponseItem::FunctionCallOutput { call_id, .. } if call_id == "call-1" + )); + } } diff --git a/codex-rs/core/src/codex_delegate.rs b/codex-rs/core/src/codex_delegate.rs index 4cb4d4a06a..fffbb991dd 100644 --- a/codex-rs/core/src/codex_delegate.rs +++ b/codex-rs/core/src/codex_delegate.rs @@ -4,6 +4,7 @@ use std::sync::atomic::AtomicU64; use async_channel::Receiver; use async_channel::Sender; use codex_async_utils::OrCancelExt; +use codex_protocol::ConversationId; use codex_protocol::protocol::ApplyPatchApprovalRequestEvent; use codex_protocol::protocol::Event; use codex_protocol::protocol::EventMsg; @@ -30,13 +31,16 @@ use codex_protocol::protocol::InitialHistory; /// The returned `events_rx` yields non-approval events emitted by the sub-agent. /// Approval requests are handled via `parent_session` and are not surfaced. /// The returned `ops_tx` allows the caller to submit additional `Op`s to the sub-agent. +#[allow(clippy::too_many_arguments)] pub(crate) async fn run_codex_conversation_interactive( config: Config, auth_manager: Arc, parent_session: Arc, parent_ctx: Arc, cancel_token: CancellationToken, + desired_conversation_id: Option, initial_history: Option, + source: SubAgentSource, ) -> Result { let (tx_sub, rx_sub) = async_channel::bounded(SUBMISSION_CHANNEL_CAPACITY); let (tx_ops, rx_ops) = async_channel::bounded(SUBMISSION_CHANNEL_CAPACITY); @@ -45,7 +49,8 @@ pub(crate) async fn run_codex_conversation_interactive( config, auth_manager, initial_history.unwrap_or(InitialHistory::New), - SessionSource::SubAgent(SubAgentSource::Review), + SessionSource::SubAgent(source), + desired_conversation_id, ) .await?; let codex = Arc::new(codex); @@ -81,6 +86,7 @@ pub(crate) async fn run_codex_conversation_interactive( next_id: AtomicU64::new(0), tx_sub: tx_ops, rx_event: rx_sub, + conversation_id: codex.conversation_id(), }) } @@ -105,13 +111,16 @@ pub(crate) async fn run_codex_conversation_one_shot( parent_session, parent_ctx, child_cancel.clone(), + None, initial_history, + SubAgentSource::Review, ) .await?; // Send the initial input to kick off the one-shot turn. io.submit(Op::UserInput { items: input }).await?; + let conversation_id = io.conversation_id(); // Bridge events so we can observe completion and shut down automatically. let (tx_bridge, rx_bridge) = async_channel::bounded(SUBMISSION_CHANNEL_CAPACITY); let ops_tx = io.tx_sub.clone(); @@ -146,6 +155,7 @@ pub(crate) async fn run_codex_conversation_one_shot( next_id: AtomicU64::new(0), rx_event: rx_bridge, tx_sub: tx_closed, + conversation_id, }) } diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 3d5f25763c..fb12dbf722 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -52,6 +52,7 @@ use std::collections::HashMap; use std::io::ErrorKind; use std::path::Path; use std::path::PathBuf; +use tracing::warn; use crate::config::profile::ConfigProfile; use toml::Value as TomlValue; @@ -70,6 +71,10 @@ pub const GPT_5_CODEX_MEDIUM_MODEL: &str = "gpt-5.1-codex"; /// the context window. pub(crate) const PROJECT_DOC_MAX_BYTES: usize = 32 * 1024; // 32 KiB +pub(crate) const DEFAULT_MAX_ACTIVE_SUBAGENTS: usize = 8; +pub(crate) const MIN_MAX_ACTIVE_SUBAGENTS: usize = 1; +pub(crate) const MAX_MAX_ACTIVE_SUBAGENTS: usize = 64; + pub(crate) const CONFIG_TOML_FILE: &str = "config.toml"; /// Application configuration loaded from disk and merged with overrides. @@ -104,6 +109,9 @@ pub struct Config { /// for either of approval_policy or sandbox_mode. pub did_user_set_custom_approval_policy_or_sandbox_mode: bool, + /// Maximum number of concurrently active subagents allowed in a session. + pub max_active_subagents: usize, + /// On Windows, indicates that a previously configured workspace-write sandbox /// was coerced to read-only because native auto mode is unsupported. pub forced_auto_mode_downgraded_on_windows: bool, @@ -128,6 +136,30 @@ pub struct Config { /// Developer instructions override injected as a separate message. pub developer_instructions: Option, + /// When true, messages from the root agent to a subagent should be + /// surfaced as `user` role messages in the child’s history instead of + /// relying solely on tool calls and inbox semantics. This is useful for + /// evaluations that compare direct user-style turns versus tool-mediated + /// messaging. When false, root-to-child communication is modeled purely + /// via tools and the subagent inbox. + pub root_agent_uses_user_messages: bool, + + /// When true, the root agent will, at turn boundaries, drain subagent + /// inboxes and inject synthetic `subagent_await` calls + outputs into the + /// message stream, and may auto-start a new turn when idle. When false, + /// subagent inboxes are only surfaced when explicitly awaited or at + /// subagent-specific yield points. + pub subagent_root_inbox_autosubmit: bool, + + /// Controls where synthetic `subagent_await` tool calls and outputs for + /// inbox delivery are injected relative to real tool call outputs inside a + /// turn. When true, inbox-derived `subagent_await` items are recorded + /// *before* tool outputs (Option B: closer to chronological ordering). When + /// false (default), they are recorded *after* tool outputs (Option A: + /// closer to training-time behavior where the model generally sees its own + /// tool call and result before additional context). + pub subagent_inbox_inject_before_tools: bool, + /// Compact prompt override. pub compact_prompt: Option, @@ -245,6 +277,7 @@ pub struct Config { pub experimental_sandbox_command_assessment: bool, /// If set to `true`, used only the experimental unified exec tool. + #[allow(dead_code)] pub use_experimental_unified_exec_tool: bool, /// If set to `true`, use the experimental official Rust MCP client. @@ -596,6 +629,30 @@ pub struct ConfigToml { /// Compact prompt used for history compaction. pub compact_prompt: Option, + /// When true, messages from the root agent to subagents should be + /// represented as `user` role messages in the child’s history. When + /// false or unset, root-to-child communication is modeled purely via + /// `subagent_send_message` and inbox delivery. + #[serde(default)] + pub root_agent_uses_user_messages: Option, + + /// When true, the root agent drains subagent inboxes at turn boundaries + /// and may auto-start new turns when idle. When false or unset, the root + /// only observes subagent inboxes via explicit `subagent_await` calls or + /// subagent-driven yield points. + #[serde(default)] + pub subagent_root_inbox_autosubmit: Option, + + /// When true, inbox-derived `subagent_await` calls and outputs are + /// injected *before* tool outputs inside a turn (Option B, closer to + /// strict chronological ordering). When false or unset, synthetic\n /// `subagent_await` entries are injected *after* tool outputs (Option A, + /// closer to training-time patterns where the model generally sees its own + /// tool call and result before extra context).\n #[serde(default)] + pub subagent_inbox_inject_before_tools: Option, + + /// Maximum number of concurrently active subagents allowed in a session. + pub max_active_subagents: Option, + /// When set, restricts ChatGPT login to a specific workspace identifier. #[serde(default)] pub forced_chatgpt_workspace_id: Option, @@ -889,6 +946,10 @@ pub struct ConfigOverrides { pub base_instructions: Option, pub developer_instructions: Option, pub compact_prompt: Option, + pub max_active_subagents: Option, + pub root_agent_uses_user_messages: Option, + pub subagent_root_inbox_autosubmit: Option, + pub subagent_inbox_inject_before_tools: Option, pub include_apply_patch_tool: Option, pub show_raw_agent_reasoning: Option, pub tools_web_search_request: Option, @@ -926,6 +987,33 @@ pub fn resolve_oss_provider( } impl Config { + /// Clone the existing config with a model override, re-deriving any model-specific fields. + pub fn clone_with_model_override(&self, model: &str) -> std::io::Result { + if model.trim().is_empty() { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "model cannot be empty", + )); + } + + let mut cfg = self.clone(); + cfg.model = model.trim().to_string(); + + let model_family = find_family_for_model(&cfg.model) + .unwrap_or_else(|| derive_default_model_family(&cfg.model)); + cfg.model_family = model_family; + + if let Some(info) = get_model_info(&cfg.model_family) { + cfg.model_context_window = Some(info.context_window); + cfg.model_auto_compact_token_limit = info.auto_compact_token_limit; + } else { + cfg.model_context_window = None; + cfg.model_auto_compact_token_limit = None; + } + + Ok(cfg) + } + /// Meant to be used exclusively for tests: `load_with_overrides()` should /// be used in all other cases. pub fn load_from_base_config_with_overrides( @@ -948,6 +1036,10 @@ impl Config { base_instructions, developer_instructions, compact_prompt, + max_active_subagents, + root_agent_uses_user_messages, + subagent_root_inbox_autosubmit: _, + subagent_inbox_inject_before_tools: _, include_apply_patch_tool: include_apply_patch_tool_override, show_raw_agent_reasoning, tools_web_search_request: override_tools_web_search_request, @@ -1080,6 +1172,7 @@ impl Config { let include_apply_patch_tool_flag = features.enabled(Feature::ApplyPatchFreeform); let tools_web_search_request = features.enabled(Feature::WebSearchRequest); + #[allow(dead_code)] let use_experimental_unified_exec_tool = features.enabled(Feature::UnifiedExec); let use_experimental_use_rmcp_client = features.enabled(Feature::RmcpClient); let experimental_sandbox_command_assessment = @@ -1162,6 +1255,37 @@ impl Config { .or(cfg.review_model) .unwrap_or_else(default_review_model); + let raw_max_active_subagents = max_active_subagents + .or(config_profile.max_active_subagents) + .or(cfg.max_active_subagents) + .unwrap_or(DEFAULT_MAX_ACTIVE_SUBAGENTS); + + if raw_max_active_subagents < MIN_MAX_ACTIVE_SUBAGENTS { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + format!( + "max_active_subagents must be at least {MIN_MAX_ACTIVE_SUBAGENTS}, got {raw_max_active_subagents}" + ), + )); + } + + let max_active_subagents = if raw_max_active_subagents > MAX_MAX_ACTIVE_SUBAGENTS { + warn!( + "max_active_subagents clamped from {} to {}", + raw_max_active_subagents, MAX_MAX_ACTIVE_SUBAGENTS + ); + MAX_MAX_ACTIVE_SUBAGENTS + } else { + raw_max_active_subagents + }; + + let root_agent_uses_user_messages = root_agent_uses_user_messages + .or(cfg.root_agent_uses_user_messages) + .unwrap_or(true); + let subagent_root_inbox_autosubmit = cfg.subagent_root_inbox_autosubmit.unwrap_or(true); + let subagent_inbox_inject_before_tools = + cfg.subagent_inbox_inject_before_tools.unwrap_or(false); + let config = Self { model, review_model, @@ -1180,6 +1304,9 @@ impl Config { user_instructions, base_instructions, developer_instructions, + root_agent_uses_user_messages, + subagent_root_inbox_autosubmit, + subagent_inbox_inject_before_tools, compact_prompt, // The config.toml omits "_mode" because it's a config file. However, "_mode" // is important in code to differentiate the mode from the store implementation. @@ -1214,6 +1341,7 @@ impl Config { .show_raw_agent_reasoning .or(show_raw_agent_reasoning) .unwrap_or(false), + max_active_subagents, model_reasoning_effort: config_profile .model_reasoning_effort .or(cfg.model_reasoning_effort), @@ -1611,6 +1739,73 @@ trust_level = "trusted" Ok(()) } + #[test] + fn max_active_subagents_defaults_and_overrides() -> std::io::Result<()> { + let temp_dir = TempDir::new()?; + + let config = Config::load_from_base_config_with_overrides( + ConfigToml::default(), + ConfigOverrides::default(), + temp_dir.path().to_path_buf(), + )?; + assert_eq!(config.max_active_subagents, DEFAULT_MAX_ACTIVE_SUBAGENTS); + + let custom = ConfigToml { + max_active_subagents: Some(3), + ..ConfigToml::default() + }; + let config = Config::load_from_base_config_with_overrides( + custom, + ConfigOverrides::default(), + temp_dir.path().to_path_buf(), + )?; + assert_eq!(config.max_active_subagents, 3); + + let overrides = ConfigOverrides { + max_active_subagents: Some(2), + ..Default::default() + }; + let config = Config::load_from_base_config_with_overrides( + ConfigToml::default(), + overrides, + temp_dir.path().to_path_buf(), + )?; + assert_eq!(config.max_active_subagents, 2); + + Ok(()) + } + + #[test] + fn max_active_subagents_validates_bounds() { + let temp_dir = TempDir::new().expect("tempdir"); + + // Below minimum should error. + let cfg_zero = ConfigToml { + max_active_subagents: Some(0), + ..ConfigToml::default() + }; + let err = Config::load_from_base_config_with_overrides( + cfg_zero, + ConfigOverrides::default(), + temp_dir.path().to_path_buf(), + ) + .expect_err("expected invalid input error"); + assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput); + + // Above ceiling should clamp. + let cfg_high = ConfigToml { + max_active_subagents: Some(MAX_MAX_ACTIVE_SUBAGENTS + 10), + ..ConfigToml::default() + }; + let config = Config::load_from_base_config_with_overrides( + cfg_high, + ConfigOverrides::default(), + temp_dir.path().to_path_buf(), + ) + .expect("clamped config"); + assert_eq!(config.max_active_subagents, MAX_MAX_ACTIVE_SUBAGENTS); + } + #[test] fn config_defaults_to_file_cli_auth_store_mode() -> std::io::Result<()> { let codex_home = TempDir::new()?; @@ -2955,6 +3150,7 @@ model_verbosity = "high" approval_policy: AskForApproval::Never, sandbox_policy: SandboxPolicy::new_read_only_policy(), did_user_set_custom_approval_policy_or_sandbox_mode: true, + max_active_subagents: DEFAULT_MAX_ACTIVE_SUBAGENTS, forced_auto_mode_downgraded_on_windows: false, shell_environment_policy: ShellEnvironmentPolicy::default(), user_instructions: None, @@ -2996,6 +3192,9 @@ model_verbosity = "high" tui_notifications: Default::default(), animations: true, otel: OtelConfig::default(), + root_agent_uses_user_messages: true, + subagent_root_inbox_autosubmit: true, + subagent_inbox_inject_before_tools: false, }, o3_profile_config ); @@ -3027,6 +3226,7 @@ model_verbosity = "high" approval_policy: AskForApproval::UnlessTrusted, sandbox_policy: SandboxPolicy::new_read_only_policy(), did_user_set_custom_approval_policy_or_sandbox_mode: true, + max_active_subagents: DEFAULT_MAX_ACTIVE_SUBAGENTS, forced_auto_mode_downgraded_on_windows: false, shell_environment_policy: ShellEnvironmentPolicy::default(), user_instructions: None, @@ -3068,6 +3268,9 @@ model_verbosity = "high" tui_notifications: Default::default(), animations: true, otel: OtelConfig::default(), + root_agent_uses_user_messages: true, + subagent_root_inbox_autosubmit: true, + subagent_inbox_inject_before_tools: false, }; assert_eq!(expected_gpt3_profile_config, gpt3_profile_config); @@ -3114,6 +3317,7 @@ model_verbosity = "high" approval_policy: AskForApproval::OnFailure, sandbox_policy: SandboxPolicy::new_read_only_policy(), did_user_set_custom_approval_policy_or_sandbox_mode: true, + max_active_subagents: DEFAULT_MAX_ACTIVE_SUBAGENTS, forced_auto_mode_downgraded_on_windows: false, shell_environment_policy: ShellEnvironmentPolicy::default(), user_instructions: None, @@ -3155,6 +3359,9 @@ model_verbosity = "high" tui_notifications: Default::default(), animations: true, otel: OtelConfig::default(), + root_agent_uses_user_messages: true, + subagent_root_inbox_autosubmit: true, + subagent_inbox_inject_before_tools: false, }; assert_eq!(expected_zdr_profile_config, zdr_profile_config); @@ -3187,6 +3394,7 @@ model_verbosity = "high" approval_policy: AskForApproval::OnFailure, sandbox_policy: SandboxPolicy::new_read_only_policy(), did_user_set_custom_approval_policy_or_sandbox_mode: true, + max_active_subagents: DEFAULT_MAX_ACTIVE_SUBAGENTS, forced_auto_mode_downgraded_on_windows: false, shell_environment_policy: ShellEnvironmentPolicy::default(), user_instructions: None, @@ -3228,6 +3436,9 @@ model_verbosity = "high" tui_notifications: Default::default(), animations: true, otel: OtelConfig::default(), + root_agent_uses_user_messages: true, + subagent_root_inbox_autosubmit: true, + subagent_inbox_inject_before_tools: false, }; assert_eq!(expected_gpt5_profile_config, gpt5_profile_config); diff --git a/codex-rs/core/src/config/profile.rs b/codex-rs/core/src/config/profile.rs index 3d9e60b8e5..69a0c51b4f 100644 --- a/codex-rs/core/src/config/profile.rs +++ b/codex-rs/core/src/config/profile.rs @@ -30,6 +30,7 @@ pub struct ConfigProfile { pub experimental_sandbox_command_assessment: Option, pub tools_web_search: Option, pub tools_view_image: Option, + pub max_active_subagents: Option, /// Optional feature toggles scoped to this profile. #[serde(default)] pub features: Option, diff --git a/codex-rs/core/src/conversation_manager.rs b/codex-rs/core/src/conversation_manager.rs index 8ffefd5679..e701be43e4 100644 --- a/codex-rs/core/src/conversation_manager.rs +++ b/codex-rs/core/src/conversation_manager.rs @@ -74,6 +74,7 @@ impl ConversationManager { auth_manager, InitialHistory::New, self.session_source.clone(), + None, ) .await?; self.finalize_spawn(codex, conversation_id).await @@ -150,6 +151,7 @@ impl ConversationManager { auth_manager, initial_history, self.session_source.clone(), + None, ) .await?; self.finalize_spawn(codex, conversation_id).await @@ -185,7 +187,14 @@ impl ConversationManager { let CodexSpawnOk { codex, conversation_id, - } = Codex::spawn(config, auth_manager, history, self.session_source.clone()).await?; + } = Codex::spawn( + config, + auth_manager, + history, + self.session_source.clone(), + None, + ) + .await?; self.finalize_spawn(codex, conversation_id).await } diff --git a/codex-rs/core/src/features.rs b/codex-rs/core/src/features.rs index 0c67c9ff5c..24b0095b0a 100644 --- a/codex-rs/core/src/features.rs +++ b/codex-rs/core/src/features.rs @@ -31,6 +31,9 @@ pub enum Feature { GhostCommit, /// Use the single unified PTY-backed exec tool. UnifiedExec, + /// Use the shell command tool that takes `command` as a single string of + /// shell instead of an array of args passed to `execvp(3)`. + ShellCommandTool, /// Enable experimental RMCP features such as OAuth login. RmcpClient, /// Include the freeform apply_patch tool. @@ -39,6 +42,8 @@ pub enum Feature { ViewImageTool, /// Allow the model to request web searches. WebSearchRequest, + /// Enable the built-in subagent orchestration tools. + SubagentTools, /// Gate the execpolicy enforcement for shell/unified exec. ExecPolicy, /// Enable the model-based risk assessments for sandboxed commands. @@ -253,25 +258,37 @@ pub struct FeatureSpec { pub const FEATURES: &[FeatureSpec] = &[ // Stable features. - FeatureSpec { - id: Feature::GhostCommit, - key: "undo", - stage: Stage::Stable, - default_enabled: true, - }, FeatureSpec { id: Feature::ViewImageTool, key: "view_image_tool", stage: Stage::Stable, default_enabled: true, }, + FeatureSpec { + id: Feature::ShellTool, + key: "shell_tool", + stage: Stage::Stable, + default_enabled: true, + }, // Unstable features. + FeatureSpec { + id: Feature::GhostCommit, + key: "ghost_commit", + stage: Stage::Experimental, + default_enabled: true, + }, FeatureSpec { id: Feature::UnifiedExec, key: "unified_exec", stage: Stage::Experimental, default_enabled: false, }, + FeatureSpec { + id: Feature::ShellCommandTool, + key: "shell_command_tool", + stage: Stage::Experimental, + default_enabled: false, + }, FeatureSpec { id: Feature::RmcpClient, key: "rmcp_client", @@ -290,6 +307,12 @@ pub const FEATURES: &[FeatureSpec] = &[ stage: Stage::Stable, default_enabled: false, }, + FeatureSpec { + id: Feature::SubagentTools, + key: "subagent_tools", + stage: Stage::Experimental, + default_enabled: false, + }, FeatureSpec { id: Feature::ExecPolicy, key: "exec_policy", @@ -320,10 +343,4 @@ pub const FEATURES: &[FeatureSpec] = &[ stage: Stage::Experimental, default_enabled: false, }, - FeatureSpec { - id: Feature::ShellTool, - key: "shell_tool", - stage: Stage::Stable, - default_enabled: true, - }, ]; diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index 6906489e7e..cb006f00b3 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -39,6 +39,7 @@ pub mod parse_command; pub mod powershell; mod response_processing; pub mod sandboxing; +pub mod subagents; mod text_encoding; pub mod token_data; mod truncate; @@ -68,6 +69,7 @@ pub mod project_doc; mod rollout; pub(crate) mod safety; pub mod seatbelt; +mod session_index; pub mod shell; pub mod spawn; pub mod terminal; @@ -116,3 +118,10 @@ pub use compact::content_items_to_text; pub use event_mapping::parse_turn_item; pub mod compact; pub mod otel_init; +pub use tools::handlers::subagent::PageDirection; +pub use tools::handlers::subagent::RenderedPage; +pub use tools::handlers::subagent::SubagentActivity; +pub use tools::handlers::subagent::classify_activity; +pub use tools::handlers::subagent::render_logs_as_text; +pub use tools::handlers::subagent::render_logs_as_text_with_max_lines; +pub use tools::handlers::subagent::render_logs_payload; diff --git a/codex-rs/core/src/response_processing.rs b/codex-rs/core/src/response_processing.rs index 458f82526a..c3d6c012f4 100644 --- a/codex-rs/core/src/response_processing.rs +++ b/codex-rs/core/src/response_processing.rs @@ -1,5 +1,3 @@ -use crate::codex::Session; -use crate::codex::TurnContext; use codex_protocol::models::FunctionCallOutputPayload; use codex_protocol::models::ResponseInputItem; use codex_protocol::models::ResponseItem; @@ -10,9 +8,7 @@ use tracing::warn; /// - `ResponseInputItem`s to send back to the model on the next turn. pub(crate) async fn process_items( processed_items: Vec, - sess: &Session, - turn_context: &TurnContext, -) -> (Vec, Vec) { +) -> (Vec, Vec, Vec) { let mut outputs_to_record = Vec::::new(); let mut new_inputs_to_record = Vec::::new(); let mut responses = Vec::::new(); @@ -60,11 +56,5 @@ pub(crate) async fn process_items( outputs_to_record.push(item); } - let all_items_to_record = [outputs_to_record, new_inputs_to_record].concat(); - // Only attempt to take the lock if there is something to record. - if !all_items_to_record.is_empty() { - sess.record_conversation_items(turn_context, &all_items_to_record) - .await; - } - (responses, all_items_to_record) + (responses, outputs_to_record, new_inputs_to_record) } diff --git a/codex-rs/core/src/rollout/policy.rs b/codex-rs/core/src/rollout/policy.rs index 9e0e308362..27297b4b78 100644 --- a/codex-rs/core/src/rollout/policy.rs +++ b/codex-rs/core/src/rollout/policy.rs @@ -84,6 +84,8 @@ pub(crate) fn should_persist_event_msg(ev: &EventMsg) -> bool { | EventMsg::ItemCompleted(_) | EventMsg::AgentMessageContentDelta(_) | EventMsg::ReasoningContentDelta(_) - | EventMsg::ReasoningRawContentDelta(_) => false, + | EventMsg::ReasoningRawContentDelta(_) + | EventMsg::AgentInbox(_) => false, + EventMsg::SubagentLifecycle(_) => true, } } diff --git a/codex-rs/core/src/session_index.rs b/codex-rs/core/src/session_index.rs new file mode 100644 index 0000000000..c445f5a4fe --- /dev/null +++ b/codex-rs/core/src/session_index.rs @@ -0,0 +1,67 @@ +use std::collections::HashMap; +use std::sync::Arc; +use std::sync::Mutex; +use std::sync::OnceLock; +use std::sync::Weak; + +use codex_protocol::ConversationId; + +use crate::codex::Session; + +struct IndexInner { + map: HashMap>, +} + +impl IndexInner { + fn new() -> Self { + Self { + map: HashMap::new(), + } + } +} + +static INDEX: OnceLock> = OnceLock::new(); + +fn idx() -> &'static Mutex { + INDEX.get_or_init(|| Mutex::new(IndexInner::new())) +} + +pub(crate) fn register(conversation_id: ConversationId, session: &Arc) { + if let Ok(mut guard) = idx().lock() { + guard.map.insert(conversation_id, Arc::downgrade(session)); + } +} + +pub(crate) fn get(conversation_id: &ConversationId) -> Option> { + let mut guard = idx().lock().ok()?; + match guard.map.get(conversation_id) { + Some(w) => w.upgrade().or_else(|| { + guard.map.remove(conversation_id); + None + }), + None => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn prunes_stale_sessions() { + let conversation_id = ConversationId::new(); + { + let mut guard = idx().lock().unwrap(); + guard.map.insert(conversation_id, Weak::new()); + } + + // First lookup should detect the dead weak ptr, prune it, and return None. + assert!(get(&conversation_id).is_none()); + + // Second lookup should see the map entry removed. + { + let guard = idx().lock().unwrap(); + assert!(!guard.map.contains_key(&conversation_id)); + } + } +} diff --git a/codex-rs/core/src/state/service.rs b/codex-rs/core/src/state/service.rs index 287fb73d25..e1bc6fe186 100644 --- a/codex-rs/core/src/state/service.rs +++ b/codex-rs/core/src/state/service.rs @@ -3,6 +3,8 @@ use std::sync::Arc; use crate::AuthManager; use crate::RolloutRecorder; use crate::mcp_connection_manager::McpConnectionManager; +use crate::subagents::SubagentManager; +use crate::subagents::SubagentRegistry; use crate::tools::sandboxing::ApprovalStore; use crate::unified_exec::UnifiedExecSessionManager; use crate::user_notification::UserNotifier; @@ -22,4 +24,6 @@ pub(crate) struct SessionServices { pub(crate) auth_manager: Arc, pub(crate) otel_event_manager: OtelEventManager, pub(crate) tool_approvals: Mutex, + pub(crate) subagents: SubagentRegistry, + pub(crate) subagent_manager: SubagentManager, } diff --git a/codex-rs/core/src/subagents/manager.rs b/codex-rs/core/src/subagents/manager.rs new file mode 100644 index 0000000000..76d5f9f885 --- /dev/null +++ b/codex-rs/core/src/subagents/manager.rs @@ -0,0 +1,3080 @@ +use std::collections::HashMap; +use std::collections::VecDeque; +use std::sync::Arc; +use std::sync::atomic::AtomicU64; +use std::sync::atomic::Ordering; +use std::time::Duration; +use std::time::SystemTime; +use std::time::UNIX_EPOCH; + +use crate::config::Config as CodexConfig; +use codex_protocol::AgentId; +use codex_protocol::ConversationId; +use codex_protocol::config_types::SandboxMode; +use codex_protocol::models::ContentItem; +use codex_protocol::models::FunctionCallOutputPayload; +use codex_protocol::models::ResponseItem; +use codex_protocol::protocol::AgentInboxEvent; +use codex_protocol::protocol::Event; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::InitialHistory; +use codex_protocol::protocol::RolloutItem; +use codex_protocol::protocol::SubAgentSource; +use codex_protocol::protocol::SubagentCreatedEvent; +use codex_protocol::protocol::SubagentLifecycleEvent; +use codex_protocol::protocol::SubagentLifecycleOrigin; +use codex_protocol::protocol::SubagentLifecycleStatus; +use codex_protocol::protocol::SubagentReasoningHeaderEvent; +use codex_protocol::protocol::SubagentRemovedEvent; +use codex_protocol::protocol::SubagentStatusEvent; +use codex_protocol::protocol::SubagentSummary; +use codex_protocol::protocol::TurnAbortReason; +use codex_protocol::user_input::UserInput; +use serde::Deserialize; +use serde::Serialize; +use serde_json::json; +use tokio::sync::Mutex; +use tokio::sync::Notify; +use tokio::sync::OwnedSemaphorePermit; +use tokio::sync::RwLock; +use tokio::sync::Semaphore; +use tokio::sync::watch; +use tokio_util::sync::CancellationToken; +use tracing::error; +use tracing::warn; + +use crate::codex::Codex; +use crate::codex::Session; +use crate::codex::TurnContext; +use crate::codex_delegate::run_codex_conversation_interactive; +use crate::error::CodexErr; +use crate::protocol::SandboxPolicy; +use crate::model_family::{derive_default_model_family, find_family_for_model}; +use codex_protocol::config_types::ReasoningEffort; +use crate::subagents::SubagentMetadata; +use crate::subagents::SubagentOrigin; +use crate::subagents::SubagentRegistry; +use crate::subagents::SubagentStatus; + +const LOG_CAPACITY: usize = 200; +const ROOT_AGENT_ID: AgentId = 0; + +#[derive(Clone)] +struct RootInboxItem { + sender_agent_id: AgentId, + timestamp_ms: i64, + payload: RootInboxPayload, + metadata: Option, +} + +#[derive(Clone)] +enum RootInboxPayload { + Message(InboxMessage), + Completion(SubagentCompletion), +} + +#[derive(Clone)] +pub struct SubagentManager { + registry: Arc, + runs: Arc>>>, + completions: Arc>>, + completed_logs: Arc>>>, + completed_inbox: Arc>>>, + root_inbox: Arc>>>, + emitters: Arc>>, + max_active_subagents: usize, + permits: Arc, + next_agent_id: Arc, + root_agent_uses_user_messages: bool, + root_inbox_autosubmit: bool, + subagent_inbox_inject_before_tools: bool, + watchdogs: Arc>>, +} + +struct WatchdogHandle { + cancel: tokio_util::sync::CancellationToken, + #[allow(dead_code)] + task: tokio::task::JoinHandle<()>, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum WatchdogAction { + Started, + Replaced, + Canceled, + NotFound, +} + +fn clamp_reasoning_effort_for_model(config: &mut CodexConfig) { + if let Some(effort) = config.model_reasoning_effort { + let family = find_family_for_model(&config.model) + .unwrap_or_else(|| derive_default_model_family(&config.model)); + if !family.supports_reasoning_summaries { + config.model_reasoning_effort = None; + return; + } + if effort == ReasoningEffort::XHigh && !config.model.starts_with("gpt-5.1-codex-max") { + config.model_reasoning_effort = Some(ReasoningEffort::High); + } + } +} + +impl SubagentManager { + fn allocate_agent_id(&self) -> AgentId { + self.next_agent_id.fetch_add(1, Ordering::Relaxed) + } + + async fn enqueue_root_inbox_completion( + &self, + root_session_id: &ConversationId, + source_session_id: &ConversationId, + completion: SubagentCompletion, + metadata: SubagentMetadata, + ) { + let now_ms = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|dur| dur.as_millis() as i64) + .unwrap_or(0); + let pending_messages = { + let mut guard = self.root_inbox.write().await; + let entry = guard.entry(*root_session_id).or_insert_with(Vec::new); + entry.push(RootInboxItem { + sender_agent_id: metadata.agent_id, + timestamp_ms: now_ms, + payload: RootInboxPayload::Completion(completion), + metadata: Some(metadata), + }); + entry.len() + }; + + let event = EventMsg::AgentInbox(AgentInboxEvent { + agent_id: ROOT_AGENT_ID, + session_id: *root_session_id, + pending_messages, + pending_interrupts: 0, + }); + self.send_event_to_parent(source_session_id, event).await; + + if self.root_inbox_autosubmit + && let Some(root_session) = crate::session_index::get(root_session_id) + && !root_session.has_active_turn().await + { + let items = self.drain_root_inbox_to_items(root_session_id).await; + if !items.is_empty() { + root_session.autosubmit_inbox_task(items).await; + } + } + } + + async fn parent_agent_id(&self, session_id: &ConversationId) -> AgentId { + self.registry + .get(session_id) + .await + .map(|m| m.agent_id) + .unwrap_or(ROOT_AGENT_ID) + } + + pub fn new( + registry: Arc, + max_active_subagents: usize, + root_agent_uses_user_messages: bool, + root_inbox_autosubmit: bool, + subagent_inbox_inject_before_tools: bool, + ) -> Self { + Self { + registry, + runs: Arc::new(RwLock::new(HashMap::new())), + completions: Arc::new(RwLock::new(HashMap::new())), + completed_logs: Arc::new(RwLock::new(HashMap::new())), + completed_inbox: Arc::new(RwLock::new(HashMap::new())), + root_inbox: Arc::new(RwLock::new(HashMap::new())), + emitters: Arc::new(RwLock::new(HashMap::new())), + max_active_subagents, + permits: Arc::new(Semaphore::new(max_active_subagents)), + next_agent_id: Arc::new(AtomicU64::new(1)), + root_agent_uses_user_messages, + root_inbox_autosubmit, + subagent_inbox_inject_before_tools, + watchdogs: Arc::new(RwLock::new(HashMap::new())), + } + } + + pub fn root_inbox_autosubmit_enabled(&self) -> bool { + self.root_inbox_autosubmit + } + + pub fn inbox_inject_before_tools(&self) -> bool { + self.subagent_inbox_inject_before_tools + } + + /// Walk parent links to find the root session for a caller. + async fn find_root_session_id(&self, session_id: ConversationId) -> Option { + let entries = self.registry.list().await; + let mut current = session_id; + loop { + let meta = entries.iter().find(|m| m.session_id == current)?; + if let Some(parent) = meta.parent_session_id { + current = parent; + continue; + } + return Some(current); + } + } + + /// Import subagent metadata from persisted rollout events (resume). + pub async fn import_from_rollout( + &self, + rollout_items: &[RolloutItem], + parent_session_id: ConversationId, + ) { + use codex_protocol::protocol::SubagentLifecycleEvent; + + let mut by_session: HashMap = HashMap::new(); + let mut watchdogs: HashMap = HashMap::new(); + let mut call_args: HashMap = HashMap::new(); + + for item in rollout_items { + match item { + RolloutItem::EventMsg(EventMsg::SubagentLifecycle(event)) => match event { + SubagentLifecycleEvent::Created(ev) => { + let meta = SubagentMetadata::from_summary(&ev.subagent); + by_session.insert(ev.subagent.session_id, meta); + } + SubagentLifecycleEvent::Status(ev) => { + if let Some(meta) = by_session.get_mut(&ev.session_id) { + meta.status = ev.status.into(); + } + } + SubagentLifecycleEvent::ReasoningHeader(ev) => { + if let Some(meta) = by_session.get_mut(&ev.session_id) { + meta.reasoning_header = Some(ev.reasoning_header.clone()); + } + } + SubagentLifecycleEvent::Deleted(ev) => { + by_session.remove(&ev.session_id); + } + }, + RolloutItem::EventMsg(EventMsg::AgentInbox(ev)) => { + if let Some(meta) = by_session.get_mut(&ev.session_id) { + meta.pending_messages = ev.pending_messages; + meta.pending_interrupts = ev.pending_interrupts; + } + } + RolloutItem::ResponseItem(ResponseItem::FunctionCall { + name, + call_id, + arguments, + .. + }) if name == "subagent_watchdog" => { + if let Ok(val) = serde_json::from_str::(arguments) { + call_args.insert(call_id.clone(), val); + } + } + RolloutItem::ResponseItem(ResponseItem::FunctionCallOutput { call_id, output }) => { + if let Some(_args) = call_args.remove(call_id) + && let Ok(val) = serde_json::from_str::(&output.content) + && let Some(agent_id) = + val.get("agent_id").and_then(serde_json::Value::as_u64) + && let Some(action) = val.get("action").and_then(|v| v.as_str()) + { + match action { + "started" | "replaced" => { + let interval = val + .get("interval_s") + .and_then(serde_json::Value::as_u64) + .unwrap_or(300); + let message = val.get("message").and_then(|v| v.as_str()).unwrap_or("Watchdog ping — report current status, next step, and PLAN.md progress.").to_string(); + watchdogs.insert(agent_id as AgentId, (interval, message)); + } + "canceled" => { + watchdogs.remove(&(agent_id as AgentId)); + } + _ => {} + } + } + } + _ => {} + } + } + + for meta in by_session.values() { + self.registry.register_imported(meta.clone()).await; + } + + for (agent_id, (interval, message)) in watchdogs { + let _ = self + .watchdog_action( + parent_session_id, + ROOT_AGENT_ID, + agent_id, + interval, + message, + false, + ) + .await; + } + } + + async fn register_emitter( + &self, + session_id: ConversationId, + session: Arc, + turn: Arc, + ) { + let emitter = SubagentEmitter { session, turn }; + self.emitters.write().await.insert(session_id, emitter); + } + + async fn remove_emitter(&self, session_id: &ConversationId) { + self.emitters.write().await.remove(session_id); + } + + async fn send_event_to_parent(&self, session_id: &ConversationId, msg: EventMsg) { + if let Some(emitter) = self.emitters.read().await.get(session_id).cloned() { + emitter.session.send_event(&emitter.turn, msg).await; + } + } + + async fn enqueue_root_inbox_message( + &self, + root_session_id: &ConversationId, + source_session_id: &ConversationId, + message: InboxMessage, + ) { + let pending_messages = { + let mut guard = self.root_inbox.write().await; + let entry = guard.entry(*root_session_id).or_insert_with(Vec::new); + entry.push(RootInboxItem { + sender_agent_id: message.sender_agent_id, + timestamp_ms: message.timestamp_ms, + payload: RootInboxPayload::Message(message), + metadata: None, + }); + entry.len() + }; + + let event = EventMsg::AgentInbox(AgentInboxEvent { + agent_id: ROOT_AGENT_ID, + session_id: *root_session_id, + pending_messages, + pending_interrupts: 0, + }); + self.send_event_to_parent(source_session_id, event).await; + + if self.root_inbox_autosubmit + && let Some(root_session) = crate::session_index::get(root_session_id) + && !root_session.has_active_turn().await + { + let items = self.drain_root_inbox_to_items(root_session_id).await; + if !items.is_empty() { + root_session.autosubmit_inbox_task(items).await; + } + } + } + + /// Drain and clear the root inbox for `root_session_id`, returning a + /// sequence of synthetic `subagent_await` call/output pairs that surface + /// all messages grouped by sending subagent. Callers are responsible for + /// recording these items into the root session's history in the desired + /// order relative to other turn items. + pub async fn drain_root_inbox_to_items( + &self, + root_session_id: &ConversationId, + ) -> Vec { + let drained: Vec = { + let mut guard = self.root_inbox.write().await; + guard.remove(root_session_id).unwrap_or_default() + }; + + if drained.is_empty() { + return Vec::new(); + } + + // Reset root inbox counts to zero for UIs. + let event = EventMsg::AgentInbox(AgentInboxEvent { + agent_id: ROOT_AGENT_ID, + session_id: *root_session_id, + pending_messages: 0, + pending_interrupts: 0, + }); + self.send_event_to_parent(root_session_id, event).await; + + #[derive(Default)] + struct RootAggregate { + messages: Vec, + completion: Option, + earliest_timestamp: i64, + metadata: Option, + } + + let mut aggregates: HashMap = HashMap::new(); + for entry in drained { + let aggregate = + aggregates + .entry(entry.sender_agent_id) + .or_insert_with(|| RootAggregate { + earliest_timestamp: entry.timestamp_ms, + metadata: entry.metadata.clone(), + ..RootAggregate::default() + }); + aggregate.earliest_timestamp = aggregate.earliest_timestamp.min(entry.timestamp_ms); + if aggregate.metadata.is_none() { + aggregate.metadata = entry.metadata.clone(); + } + match entry.payload { + RootInboxPayload::Message(msg) => aggregate.messages.push(msg), + RootInboxPayload::Completion(completion) => aggregate.completion = Some(completion), + } + } + + let registry_entries = self.registry.list().await; + let mut items = Vec::new(); + let mut aggregates_vec: Vec<(AgentId, RootAggregate)> = aggregates.into_iter().collect(); + aggregates_vec.sort_by_key(|(_, aggregate)| aggregate.earliest_timestamp); + + for (sender_agent_id, mut aggregate) in aggregates_vec { + if aggregate.messages.is_empty() && aggregate.completion.is_none() { + continue; + } + + // Prefer metadata captured at enqueue time, but fall back to the registry. + let metadata = aggregate + .metadata + .or_else(|| { + registry_entries + .iter() + .find(|m| { + m.agent_id == sender_agent_id + && m.parent_session_id == Some(*root_session_id) + }) + .cloned() + }) + .or_else(|| { + if sender_agent_id == ROOT_AGENT_ID { + let now = SystemTime::now(); + let now_ms = now + .duration_since(UNIX_EPOCH) + .map(|d| d.as_millis() as i64) + .unwrap_or(0); + Some(SubagentMetadata { + agent_id: ROOT_AGENT_ID, + parent_agent_id: None, + session_id: *root_session_id, + parent_session_id: None, + origin: SubagentOrigin::Spawn, + initial_message_count: 0, + status: SubagentStatus::Ready, + created_at: now, + created_at_ms: now_ms, + session_key: root_session_id.to_string(), + label: Some("root".to_string()), + summary: None, + reasoning_header: None, + pending_messages: 0, + pending_interrupts: 0, + }) + } else { + None + } + }); + let Some(metadata) = metadata else { + continue; + }; + + aggregate.messages.sort_by_key(|m| m.timestamp_ms); + + let call_id = format!("await-{sender_agent_id}"); + let arguments = serde_json::json!({ + "timeout_s": 0, + }) + .to_string(); + + let call_item = ResponseItem::FunctionCall { + id: None, + name: "subagent_await".to_string(), + arguments, + call_id: call_id.clone(), + }; + + let lifecycle_status = metadata.status; + let started_at_ms = metadata.created_at_ms; + let completion_status = aggregate + .completion + .as_ref() + .map(crate::tools::handlers::subagent::completion_status); + let response_body = serde_json::json!({ + "session_id": metadata.session_id, + "completion_status": completion_status, + "lifecycle_status": lifecycle_status, + "started_at_ms": started_at_ms, + "timed_out": false, + "messages": aggregate.messages, + "completion": aggregate.completion, + "metadata": metadata, + "injected": true, + }) + .to_string(); + + let output_item = ResponseItem::FunctionCallOutput { + call_id: call_id.clone(), + output: FunctionCallOutputPayload { + content: response_body, + content_items: None, + success: Some(true), + }, + }; + + items.push(call_item); + items.push(output_item); + } + + items + } + + async fn update_inbox_counts_and_emit( + &self, + session_id: &ConversationId, + pending_messages: usize, + pending_interrupts: usize, + ) { + if let Some(metadata) = self + .registry + .update_inbox_counts(session_id, pending_messages, pending_interrupts) + .await + { + self.emit_inbox(&metadata).await; + } + } + + async fn emit_inbox(&self, metadata: &SubagentMetadata) { + let msg = EventMsg::AgentInbox(AgentInboxEvent { + agent_id: metadata.agent_id, + session_id: metadata.session_id, + pending_messages: metadata.pending_messages, + pending_interrupts: metadata.pending_interrupts, + }); + self.send_event_to_parent(&metadata.session_id, msg).await; + } + + async fn emit_created(&self, metadata: &SubagentMetadata) { + let summary = to_subagent_summary(metadata); + let event = + EventMsg::SubagentLifecycle(SubagentLifecycleEvent::Created(SubagentCreatedEvent { + subagent: summary, + })); + self.send_event_to_parent(&metadata.session_id, event).await; + } + + /// Helper to synthesize a `subagent_await` tool call and corresponding + /// output into the given session's history. Callers are responsible for + /// choosing the appropriate target session (parent vs. child) and for + /// deciding which subset of messages should be delivered. + async fn inject_synthetic_await_into_session( + &self, + target_session_id: &ConversationId, + agent_id: AgentId, + metadata: &SubagentMetadata, + messages: &[InboxMessage], + completion: Option<&SubagentCompletion>, + ) { + if messages.is_empty() && completion.is_none() { + return; + } + + let Some(session) = crate::session_index::get(target_session_id) else { + return; + }; + let turn = session + .new_turn(crate::codex::SessionSettingsUpdate::default()) + .await; + + // Synthesize a tool call + output pair that matches the + // `subagent_await` tool schema. Use a stable call id for ease of + // debugging; uniqueness is not required for tests. + let call_id = format!("await-{agent_id}"); + let arguments = serde_json::json!({ + "timeout_s": 0, + }) + .to_string(); + + let call_item = ResponseItem::FunctionCall { + id: None, + name: "subagent_await".to_string(), + arguments, + call_id: call_id.clone(), + }; + + let completion_status = completion.map(crate::tools::handlers::subagent::completion_status); + let lifecycle_status = metadata.status; + let started_at_ms = metadata.created_at_ms; + let response_body = serde_json::json!({ + "session_id": metadata.session_id, + "completion_status": completion_status, + "lifecycle_status": lifecycle_status, + "started_at_ms": started_at_ms, + "timed_out": false, + "messages": messages, + "completion": completion, + "metadata": metadata, + "injected": true, + }) + .to_string(); + + let output_item = ResponseItem::FunctionCallOutput { + call_id: call_id.clone(), + output: FunctionCallOutputPayload { + content: response_body, + content_items: None, + success: Some(true), + }, + }; + + session + .record_conversation_items(&turn, &[call_item, output_item]) + .await; + } + + /// Deliver a batch of inbox messages and optional completion into the + /// child session's history so the subagent itself can see messages in its + /// own thread, honoring the `root_agent_uses_user_messages` toggle. + pub(crate) async fn deliver_inbox_to_threads_at_yield(&self, result: &AwaitInboxResult) { + let metadata = &result.metadata; + let messages = &result.messages; + let completion = result.completion.as_ref(); + + if messages.is_empty() && completion.is_none() { + return; + } + + // For the child session, either deliver all messages via a synthetic + // subagent_await (tool-only mode) or split them so that root-origin + // messages become user turns while messages from other agents are + // surfaced via subagent_await. + let child_session_id = metadata.session_id; + + if self.root_agent_uses_user_messages && !messages.is_empty() { + let mut from_root = Vec::new(); + let mut from_others = Vec::new(); + for msg in messages { + if msg.sender_agent_id == ROOT_AGENT_ID { + from_root.push(msg.clone()); + } else { + from_others.push(msg.clone()); + } + } + + if !from_others.is_empty() || completion.is_some() { + self.inject_synthetic_await_into_session( + &child_session_id, + metadata.agent_id, + metadata, + &from_others, + completion, + ) + .await; + } + + if !from_root.is_empty() + && let Some(child_session) = crate::session_index::get(&child_session_id) + { + let turn = child_session + .new_turn(crate::codex::SessionSettingsUpdate::default()) + .await; + let mut items = Vec::new(); + + for msg in from_root { + if let Some(prompt) = msg.prompt.clone() { + let trimmed = prompt.trim(); + if trimmed.is_empty() { + continue; + } + items.push(ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: trimmed.to_string(), + }], + }); + } + } + + if !items.is_empty() { + child_session.record_conversation_items(&turn, &items).await; + } + } + } else { + // Tool-only mode: all messages are delivered via a synthetic + // subagent_await call in the child history. + self.inject_synthetic_await_into_session( + &child_session_id, + metadata.agent_id, + metadata, + messages, + completion, + ) + .await; + } + } + + async fn emit_status(&self, session_id: &ConversationId, status: SubagentStatus) { + let agent_id = self + .registry + .get(session_id) + .await + .map(|m| m.agent_id) + .unwrap_or(ROOT_AGENT_ID); + let event = + EventMsg::SubagentLifecycle(SubagentLifecycleEvent::Status(SubagentStatusEvent { + agent_id, + session_id: *session_id, + status: status.into(), + })); + self.send_event_to_parent(session_id, event).await; + } + + async fn emit_reasoning_header(&self, session_id: &ConversationId, header: String) { + let agent_id = self + .registry + .get(session_id) + .await + .map(|m| m.agent_id) + .unwrap_or(ROOT_AGENT_ID); + let event = EventMsg::SubagentLifecycle(SubagentLifecycleEvent::ReasoningHeader( + SubagentReasoningHeaderEvent { + agent_id, + session_id: *session_id, + reasoning_header: header, + }, + )); + self.send_event_to_parent(session_id, event).await; + } + + async fn emit_deleted(&self, session_id: &ConversationId) { + let agent_id = self + .registry + .get(session_id) + .await + .map(|m| m.agent_id) + .unwrap_or(ROOT_AGENT_ID); + let event = + EventMsg::SubagentLifecycle(SubagentLifecycleEvent::Deleted(SubagentRemovedEvent { + agent_id, + session_id: *session_id, + })); + self.send_event_to_parent(session_id, event).await; + } + + async fn update_status_and_emit(&self, session_id: &ConversationId, status: SubagentStatus) { + let _ = self.registry.update_status(session_id, status).await; + self.emit_status(session_id, status).await; + } + + async fn update_reasoning_header_and_emit(&self, session_id: &ConversationId, header: String) { + let header_clone = header.clone(); + if self + .registry + .update_reasoning_header(session_id, header) + .await + .is_some() + { + self.emit_reasoning_header(session_id, header_clone).await; + } + } + + pub(crate) async fn spawn( + &self, + session: Arc, + turn: Arc, + request: SpawnRequest, + ) -> Result { + let session_id = ConversationId::new(); + let parent_agent_id = self.parent_agent_id(&session.conversation_id()).await; + let agent_id = self.allocate_agent_id(); + let metadata = self + .registry + .register_spawn( + session_id, + Some(session.conversation_id()), + Some(parent_agent_id), + agent_id, + 0, + request.label.clone(), + request.summary.clone(), + ) + .await; + + self.register_emitter(session_id, Arc::clone(&session), Arc::clone(&turn)) + .await; + self.emit_created(&metadata).await; + self.emit_inbox(&metadata).await; + + let launch = self + .launch_child( + session_id, + Arc::clone(&session), + Arc::clone(&turn), + None, + request.sandbox_mode, + request.model, + ) + .await; + let runtime = match launch { + Ok(runtime) => runtime, + Err(err) => { + self.emit_deleted(&session_id).await; + self.remove_emitter(&session_id).await; + self.registry.remove(&session_id).await; + return Err(err); + } + }; + + match runtime.submit_prompt(&request.prompt).await { + Ok(true) => { + self.update_status_and_emit(&session_id, SubagentStatus::Running) + .await; + } + Ok(false) => { + self.update_status_and_emit(&session_id, SubagentStatus::Ready) + .await; + } + Err(err) => { + self.handle_launch_failure(session_id, runtime.clone(), err) + .await; + return Err(SubagentManagerError::LaunchFailed( + "failed to submit initial prompt".to_string(), + )); + } + } + + let final_metadata = self.registry.get(&session_id).await.unwrap_or(metadata); + Ok(final_metadata) + } + + pub(crate) async fn fork( + &self, + session: Arc, + turn: Arc, + request: ForkRequest, + ) -> Result { + let session_id = ConversationId::new(); + let metadata = self + .registry + .register_fork( + session_id, + request.parent_session_id, + Some(self.parent_agent_id(&request.parent_session_id).await), + self.allocate_agent_id(), + request.initial_message_count, + request.label.clone(), + request.summary.clone(), + ) + .await; + + self.register_emitter(session_id, Arc::clone(&session), Arc::clone(&turn)) + .await; + self.emit_created(&metadata).await; + self.emit_inbox(&metadata).await; + + let mut fork_items = build_fork_history(Arc::clone(&session)) + .await + .get_rollout_items(); + // Remove the parent's fork call/output so the child history only contains the synthetic entry. + remove_call_items(&mut fork_items, &request.call_id); + // Append synthetic fork call/return so the child sees the fork result. + let child_payload_json = json!({ + "role": "child", + "parent_session_id": request.parent_session_id, + "child_session_id": session_id, + "label": request.label, + "summary": request.summary, + "prompt": request.prompt, + }) + .to_string(); + let synthetic_call = ResponseItem::FunctionCall { + id: None, + name: "subagent_fork".to_string(), + arguments: request.arguments.clone(), + call_id: request.call_id.clone(), + }; + let synthetic_return = ResponseItem::FunctionCallOutput { + call_id: request.call_id.clone(), + output: FunctionCallOutputPayload { + content: child_payload_json, + content_items: None, + success: Some(true), + }, + }; + fork_items.push(RolloutItem::ResponseItem(synthetic_call)); + fork_items.push(RolloutItem::ResponseItem(synthetic_return)); + let launch = self + .launch_child( + session_id, + Arc::clone(&session), + Arc::clone(&turn), + Some(InitialHistory::Forked(fork_items)), + request.sandbox_mode, + request.model, + ) + .await; + let runtime = match launch { + Ok(runtime) => runtime, + Err(err) => { + self.emit_deleted(&session_id).await; + self.remove_emitter(&session_id).await; + self.registry.remove(&session_id).await; + return Err(err); + } + }; + + let trimmed_prompt = request + .prompt + .as_ref() + .map(|p| p.trim()) + .filter(|p| !p.is_empty()) + .map(str::to_string); + + match trimmed_prompt { + Some(prompt) => match runtime.submit_prompt(&prompt).await { + Ok(true) => { + self.update_status_and_emit(&session_id, SubagentStatus::Running) + .await; + } + Ok(false) => { + self.update_status_and_emit(&session_id, SubagentStatus::Ready) + .await; + } + Err(err) => { + self.handle_launch_failure(session_id, runtime.clone(), err) + .await; + return Err(SubagentManagerError::LaunchFailed( + "failed to submit initial prompt".to_string(), + )); + } + }, + None => { + self.update_status_and_emit(&session_id, SubagentStatus::Ready) + .await; + } + } + + let final_metadata = self.registry.get(&session_id).await.unwrap_or(metadata); + Ok(final_metadata) + } + + pub async fn send_message( + &self, + request: SendMessageRequest, + ) -> Result { + let SendMessageRequest { + session_id, + label, + summary, + prompt, + agent_id, + sender_agent_id, + interrupt, + } = request; + let runtime = { + let runs = self.runs.read().await; + runs.get(&session_id).cloned() + } + .ok_or(SubagentManagerError::NotFound)?; + + let existing = self + .registry + .get(&session_id) + .await + .ok_or(SubagentManagerError::NotFound)?; + + if existing.agent_id != agent_id { + return Err(SubagentManagerError::AgentIdMismatch { + session_id, + agent_id, + }); + } + + let updated_label = label.or(existing.label.clone()); + let updated_summary = summary.or(existing.summary.clone()); + + let metadata = self + .registry + .update_label_and_summary(&session_id, updated_label, updated_summary) + .await + .ok_or(SubagentManagerError::NotFound)?; + + // Keep prior completions/logs intact so history reflects previous turns. + // Only clear the runtime's in-flight completion latch so new work can proceed. + runtime.clear_completion(); + let trimmed_prompt = prompt + .as_ref() + .map(|text| text.trim()) + .filter(|text| !text.is_empty()) + .map(std::string::ToString::to_string); + + if interrupt || trimmed_prompt.is_some() { + let counts = runtime + .enqueue_message(PendingMessage { + prompt: trimmed_prompt.clone(), + interrupt, + }) + .await; + self.update_inbox_counts_and_emit(&session_id, counts.0, counts.1) + .await; + } + + // Record a logical inbox message so callers of subagent_await can see + // who sent what, even though the underlying runtime is still driven by + // UserInput events via the mailbox. + let now_ms = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|dur| dur.as_millis() as i64) + .unwrap_or(0); + let inbox_message = InboxMessage { + sender_agent_id, + recipient_agent_id: agent_id, + interrupt, + prompt: trimmed_prompt.clone(), + timestamp_ms: now_ms, + }; + let _ = runtime.enqueue_inbox_message(inbox_message).await; + + if interrupt { + runtime.interrupt().await; + } + + if trimmed_prompt.is_some() { + self.update_status_and_emit(&session_id, SubagentStatus::Running) + .await; + } else { + self.update_status_and_emit(&session_id, SubagentStatus::Ready) + .await; + } + + let final_metadata = self.registry.get(&session_id).await.unwrap_or(metadata); + Ok(final_metadata) + } + + pub async fn watchdog_action( + &self, + caller_session_id: ConversationId, + caller_agent_id: AgentId, + target_agent_id: AgentId, + interval_s: u64, + message: String, + cancel: bool, + ) -> Result { + if cancel { + return Ok(self + .cancel_watchdog(&caller_session_id, target_agent_id) + .await); + } + + let root_session_id = if target_agent_id == ROOT_AGENT_ID { + self.find_root_session_id(caller_session_id) + .await + .unwrap_or(caller_session_id) + } else { + caller_session_id + }; + + let target_session_id = if target_agent_id == ROOT_AGENT_ID { + root_session_id + } else { + self.registry + .list() + .await + .into_iter() + .find(|m| m.agent_id == target_agent_id) + .map(|m| m.session_id) + .ok_or(SubagentManagerError::NotFound)? + }; + + let action = self + .start_watchdog( + caller_session_id, + root_session_id, + caller_agent_id, + target_session_id, + target_agent_id, + interval_s, + message, + ) + .await?; + Ok(action) + } + + async fn start_watchdog( + &self, + caller_session_id: ConversationId, + root_session_id: ConversationId, + caller_agent_id: AgentId, + target_session_id: ConversationId, + target_agent_id: AgentId, + interval_s: u64, + message: String, + ) -> Result { + let key = (caller_session_id, target_agent_id); + + if let Some(existing) = self.watchdogs.write().await.remove(&key) { + existing.cancel.cancel(); + } + + let cancel = tokio_util::sync::CancellationToken::new(); + let cancel_child = cancel.clone(); + let manager = self.clone(); + let msg_clone = message.clone(); + let task = tokio::spawn(async move { + loop { + tokio::select! { + _ = cancel_child.cancelled() => break, + _ = tokio::time::sleep(Duration::from_secs(interval_s)) => { + if cancel_child.is_cancelled() { + break; + } + if target_agent_id == ROOT_AGENT_ID { + if caller_agent_id == ROOT_AGENT_ID { + let now_ms = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_millis() as i64) + .unwrap_or(0); + let inbox = InboxMessage { + sender_agent_id: ROOT_AGENT_ID, + recipient_agent_id: ROOT_AGENT_ID, + interrupt: false, + prompt: Some(msg_clone.clone()), + timestamp_ms: now_ms, + }; + manager + .enqueue_root_inbox_message( + &root_session_id, + &caller_session_id, + inbox, + ) + .await; + } else if let Some(sender_meta) = manager.registry.get(&caller_session_id).await { + let _ = manager + .send_message_to_root( + root_session_id, + caller_session_id, + Some(msg_clone.clone()), + sender_meta, + ) + .await; + } else { + warn!(caller_session_id = %caller_session_id, "watchdog could not find sender metadata; stopping watchdog"); + break; + } + } else { + let request = SendMessageRequest { + session_id: target_session_id, + label: None, + summary: None, + prompt: Some(msg_clone.clone()), + agent_id: target_agent_id, + sender_agent_id: caller_agent_id, + interrupt: false, + }; + if let Err(err) = manager.send_message(request).await { + warn!(?err, "watchdog send_message failed; stopping watchdog"); + break; + } + } + } + } + } + }); + + let replaced = self + .watchdogs + .write() + .await + .insert(key, WatchdogHandle { cancel, task }) + .is_some(); + Ok(if replaced { + WatchdogAction::Replaced + } else { + WatchdogAction::Started + }) + } + + async fn cancel_watchdog( + &self, + parent_session_id: &ConversationId, + target_agent_id: AgentId, + ) -> WatchdogAction { + let key = (*parent_session_id, target_agent_id); + if let Some(handle) = self.watchdogs.write().await.remove(&key) { + handle.cancel.cancel(); + WatchdogAction::Canceled + } else { + WatchdogAction::NotFound + } + } + + pub async fn send_message_to_root( + &self, + root_session_id: ConversationId, + source_session_id: ConversationId, + prompt: Option, + sender_metadata: SubagentMetadata, + ) -> Result<(), SubagentManagerError> { + let trimmed_prompt = prompt + .as_ref() + .map(|text| text.trim()) + .filter(|text| !text.is_empty()) + .map(std::string::ToString::to_string); + + if trimmed_prompt.is_none() { + return Ok(()); + } + + let now_ms = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|dur| dur.as_millis() as i64) + .unwrap_or(0); + let inbox_message = InboxMessage { + sender_agent_id: sender_metadata.agent_id, + recipient_agent_id: ROOT_AGENT_ID, + interrupt: false, + prompt: trimmed_prompt, + timestamp_ms: now_ms, + }; + + self.enqueue_root_inbox_message(&root_session_id, &source_session_id, inbox_message) + .await; + + Ok(()) + } + + pub async fn cancel( + &self, + session_id: ConversationId, + ) -> Result { + let metadata = self + .registry + .get(&session_id) + .await + .ok_or(SubagentManagerError::NotFound)?; + + if is_terminal_status(metadata.status) { + return Ok(metadata); + } + + if let Some(runtime) = { + let runs = self.runs.read().await; + runs.get(&session_id).cloned() + } { + self.finalize_terminal( + &session_id, + runtime, + SubagentCompletion::Canceled { + reason: TurnAbortReason::Interrupted, + }, + SubagentStatus::Canceled, + ) + .await; + } else { + let completion = SubagentCompletion::Canceled { + reason: TurnAbortReason::Interrupted, + }; + self.update_status_and_emit(&session_id, SubagentStatus::Canceled) + .await; + { + let mut completions = self.completions.write().await; + completions.insert(session_id, completion.clone()); + } + { + let mut logs = self.completed_logs.write().await; + logs.entry(session_id).or_insert_with(Vec::new); + } + { + let mut inbox = self.completed_inbox.write().await; + inbox.entry(session_id).or_insert_with(Vec::new); + } + self.remove_runtime_entry(&session_id).await; + } + + let updated = self + .registry + .get(&session_id) + .await + .ok_or(SubagentManagerError::NotFound)?; + Ok(updated) + } + + pub async fn metadata(&self, session_id: &ConversationId) -> Option { + self.registry.get(session_id).await + } + + /// Returns a snapshot of the in-memory log buffer for a running subagent. + /// + /// Entries are ordered from oldest to newest. The buffer already only + /// contains events since the child was spawned/forked. + pub async fn snapshot_logs( + &self, + session_id: &ConversationId, + ) -> Result, SubagentManagerError> { + if let Some(runtime) = { + let runs = self.runs.read().await; + runs.get(session_id).cloned() + } { + let guard = runtime.logs.lock().await; + let entries = guard.iter().map(LogEntry::from_logged).collect::>(); + Ok(entries) + } else { + let logs = self.completed_logs.read().await; + let snapshot = logs + .get(session_id) + .cloned() + .ok_or(SubagentManagerError::NotFound)?; + let entries = snapshot + .into_iter() + .map(|logged| LogEntry::from_logged(&logged)) + .collect(); + Ok(entries) + } + } + + pub async fn await_completion( + &self, + session_id: &ConversationId, + timeout: Option, + ) -> Result { + if let Some(completion) = { + let completions = self.completions.read().await; + completions.get(session_id).cloned() + } { + let desired_status = status_from_completion(&completion); + let metadata = self + .registry + .get(session_id) + .await + .ok_or(SubagentManagerError::NotFound)?; + if metadata.status != desired_status { + self.update_status_and_emit(session_id, desired_status) + .await; + let metadata = self + .registry + .get(session_id) + .await + .ok_or(SubagentManagerError::NotFound)?; + return Ok(AwaitResult { + metadata, + completion, + }); + } + return Ok(AwaitResult { + metadata, + completion, + }); + } + + let runtime = { + let runs = self.runs.read().await; + runs.get(session_id).cloned() + }; + let runtime = match runtime { + Some(runtime) => runtime, + None => { + if let Some(completion) = { + let completions = self.completions.read().await; + completions.get(session_id).cloned() + } { + let metadata = self + .registry + .get(session_id) + .await + .ok_or(SubagentManagerError::NotFound)?; + return Ok(AwaitResult { + metadata, + completion, + }); + } + return Err(SubagentManagerError::NotFound); + } + }; + let mut receiver = runtime.completion_receiver(); + + if let Some(completion) = current_completion(&receiver) { + let metadata = self + .registry + .get(session_id) + .await + .ok_or(SubagentManagerError::NotFound)?; + return Ok(AwaitResult { + metadata, + completion, + }); + } + + let timeout_total = timeout; + let start = tokio::time::Instant::now(); + let mut completion_opt = None; + loop { + let changed = if let Some(duration) = timeout_total { + let elapsed = start.elapsed(); + if elapsed >= duration { + let timeout_ms = duration.as_millis().try_into().unwrap_or(u64::MAX); + let agent_id = self + .registry + .get(session_id) + .await + .map(|m| m.agent_id) + .unwrap_or(ROOT_AGENT_ID); + return Err(SubagentManagerError::AwaitTimedOut { + session_id: *session_id, + agent_id, + timeout_ms, + }); + } + let remaining = duration - elapsed; + match tokio::time::timeout(remaining, receiver.changed()).await { + Ok(result) => result, + Err(_) => { + let timeout_ms = duration.as_millis().try_into().unwrap_or(u64::MAX); + let agent_id = self + .registry + .get(session_id) + .await + .map(|m| m.agent_id) + .unwrap_or(ROOT_AGENT_ID); + return Err(SubagentManagerError::AwaitTimedOut { + session_id: *session_id, + agent_id, + timeout_ms, + }); + } + } + } else { + receiver.changed().await + }; + + match changed { + Ok(()) => { + if let Some(completion) = current_completion(&receiver) { + completion_opt = Some(completion); + break; + } + } + Err(_) => break, + } + } + + let completion = if let Some(completion) = completion_opt { + completion + } else { + let completions = self.completions.read().await; + completions + .get(session_id) + .cloned() + .ok_or(SubagentManagerError::NotFound)? + }; + + { + let mut completions = self.completions.write().await; + completions.insert(*session_id, completion.clone()); + } + + let desired_status = status_from_completion(&completion); + if let Some(current) = self.registry.get(session_id).await + && current.status != desired_status + { + self.update_status_and_emit(session_id, desired_status) + .await; + } + + let metadata = self + .registry + .get(session_id) + .await + .ok_or(SubagentManagerError::NotFound)?; + Ok(AwaitResult { + metadata, + completion, + }) + } + + /// Wait for either new inbox messages or a completion for the given + /// session. This is the backing implementation for the `subagent_await` + /// tool and is intentionally conservative: it mirrors the existing + /// completion semantics while layering inbox delivery on top. + pub async fn await_inbox_and_completion( + &self, + session_id: &ConversationId, + timeout: Option, + ) -> Result { + // If we already have a stored completion and no runtime, there is + // nothing left to wait for; return the terminal state with an empty + // message list. + if let Some(completion) = { + let completions = self.completions.read().await; + completions.get(session_id).cloned() + } { + let metadata = self + .registry + .get(session_id) + .await + .ok_or(SubagentManagerError::NotFound)?; + return Ok(AwaitInboxResult { + metadata, + completion: Some(completion), + messages: Vec::new(), + }); + } + + let runtime = { + let runs = self.runs.read().await; + runs.get(session_id).cloned() + }; + let runtime = match runtime { + Some(runtime) => runtime, + None => { + if let Some(completion) = { + let completions = self.completions.read().await; + completions.get(session_id).cloned() + } { + let metadata = self + .registry + .get(session_id) + .await + .ok_or(SubagentManagerError::NotFound)?; + return Ok(AwaitInboxResult { + metadata, + completion: Some(completion), + messages: Vec::new(), + }); + } + return Err(SubagentManagerError::NotFound); + } + }; + + let mut receiver = runtime.completion_receiver(); + let inbox_notify = runtime.inbox_notifier(); + + // Fast path: if there are already inbox messages or a completion, + // return immediately without waiting. + let mut messages = runtime.drain_inbox().await; + let mut completion_opt = current_completion(&receiver); + if completion_opt.is_some() || !messages.is_empty() { + if let Some(ref completion) = completion_opt { + let desired_status = status_from_completion(completion); + self.update_status_and_emit(session_id, desired_status) + .await; + { + let mut completions = self.completions.write().await; + completions.insert(*session_id, completion.clone()); + } + } + let metadata = self + .registry + .get(session_id) + .await + .ok_or(SubagentManagerError::NotFound)?; + return Ok(AwaitInboxResult { + metadata, + completion: completion_opt, + messages, + }); + } + + let timeout_total = timeout; + let start = tokio::time::Instant::now(); + + loop { + // Helper for computing remaining timeout and converting expirations + // into the existing AwaitTimedOut error. + let remaining = if let Some(duration) = timeout_total { + let elapsed = start.elapsed(); + if elapsed >= duration { + let timeout_ms = duration.as_millis().try_into().unwrap_or(u64::MAX); + let agent_id = self + .registry + .get(session_id) + .await + .map(|m| m.agent_id) + .unwrap_or(ROOT_AGENT_ID); + return Err(SubagentManagerError::AwaitTimedOut { + session_id: *session_id, + agent_id, + timeout_ms, + }); + } + Some(duration - elapsed) + } else { + None + }; + + if let Some(rem) = remaining { + tokio::select! { + _ = tokio::time::sleep(rem) => { + let timeout_ms = timeout_total + .map(|d| d.as_millis().try_into().unwrap_or(u64::MAX)) + .unwrap_or(0); + let agent_id = self + .registry + .get(session_id) + .await + .map(|m| m.agent_id) + .unwrap_or(ROOT_AGENT_ID); + return Err(SubagentManagerError::AwaitTimedOut { + session_id: *session_id, + agent_id, + timeout_ms, + }); + } + _ = inbox_notify.notified() => { + let new_messages = runtime.drain_inbox().await; + if !new_messages.is_empty() { + messages.extend(new_messages); + break; + } + // Spurious wakeup or inbox drained by another waiter; + // loop and wait again. + } + changed = receiver.changed() => { + match changed { + Ok(()) => { + if let Some(completion) = current_completion(&receiver) { + completion_opt = Some(completion); + break; + } + } + Err(_) => break, + } + } + } + } else { + tokio::select! { + _ = inbox_notify.notified() => { + let new_messages = runtime.drain_inbox().await; + if !new_messages.is_empty() { + messages.extend(new_messages); + break; + } + } + changed = receiver.changed() => { + match changed { + Ok(()) => { + if let Some(completion) = current_completion(&receiver) { + completion_opt = Some(completion); + break; + } + } + Err(_) => break, + } + } + } + } + } + + // Finalize completion state if we observed a terminal result. + if let Some(ref completion) = completion_opt { + let desired_status = status_from_completion(completion); + self.update_status_and_emit(session_id, desired_status) + .await; + { + let mut completions = self.completions.write().await; + completions.insert(*session_id, completion.clone()); + } + } + + let metadata = self + .registry + .get(session_id) + .await + .ok_or(SubagentManagerError::NotFound)?; + + Ok(AwaitInboxResult { + metadata, + completion: completion_opt, + messages, + }) + } + + pub async fn prune(&self, request: PruneRequest) -> Result { + if !request.all { + if let Some(ids) = &request.session_ids { + if ids.is_empty() { + return Err(SubagentManagerError::InvalidPruneRequest( + "session_ids list cannot be empty".to_string(), + )); + } + } else { + return Err(SubagentManagerError::InvalidPruneRequest( + "specify session_ids or set all=true".to_string(), + )); + } + } + + let mut report = PruneReport::default(); + + if let Some(ids) = &request.session_ids { + for id in ids { + self.prune_single(*id, request.completed_only, &mut report) + .await; + } + } else { + let entries = self.registry.list().await; + for metadata in entries { + self.prune_with_metadata(metadata, request.completed_only, &mut report) + .await; + } + } + + Ok(report) + } + + async fn prune_single( + &self, + session_id: ConversationId, + completed_only: bool, + report: &mut PruneReport, + ) { + if let Some(metadata) = self.registry.get(&session_id).await { + self.prune_with_metadata(metadata, completed_only, report) + .await; + } else { + if let Some(runtime) = { + let mut runs = self.runs.write().await; + runs.remove(&session_id) + } { + runtime.shutdown().await; + } + { + let mut completions = self.completions.write().await; + completions.remove(&session_id); + } + { + let mut logs = self.completed_logs.write().await; + logs.remove(&session_id); + } + { + let mut inbox = self.completed_inbox.write().await; + inbox.remove(&session_id); + } + report.unknown.push(session_id); + } + } + + async fn prune_with_metadata( + &self, + metadata: SubagentMetadata, + completed_only: bool, + report: &mut PruneReport, + ) { + let session_id = metadata.session_id; + if completed_only && !is_terminal_status(metadata.status) { + report.skipped_active.push(session_id); + return; + } + + if let Some(runtime) = { + let mut runs = self.runs.write().await; + runs.remove(&session_id) + } { + runtime.shutdown().await; + } + + { + let mut completions = self.completions.write().await; + completions.remove(&session_id); + } + { + let mut logs = self.completed_logs.write().await; + logs.remove(&session_id); + } + { + let mut inbox = self.completed_inbox.write().await; + inbox.remove(&session_id); + } + + self.emit_deleted(&session_id).await; + self.remove_emitter(&session_id).await; + + if self.registry.remove(&session_id).await.is_some() { + report.pruned.push(session_id); + } else { + report.unknown.push(session_id); + } + } + + async fn launch_child( + &self, + session_id: ConversationId, + session: Arc, + turn: Arc, + initial_history: Option, + sandbox_override: Option, + model_override: Option, + ) -> Result, SubagentManagerError> { + let permit = self.permits.clone().try_acquire_owned().map_err(|_| { + SubagentManagerError::LimitReached { + limit: self.max_active_subagents, + } + })?; + let mut config: CodexConfig = turn.client.config().as_ref().clone(); + if let Some(model) = model_override.as_ref() { + config = config.clone_with_model_override(model).map_err(|err| { + SubagentManagerError::LaunchFailed(format!( + "invalid model `{model}` for subagent: {err}" + )) + })?; + } + // Ensure the subagent's reasoning settings are valid for its model. + clamp_reasoning_effort_for_model(&mut config); + let parent_policy = turn.sandbox_policy.clone(); + if let Some(requested) = sandbox_override { + let parent_mode = sandbox_mode_from_policy(&parent_policy); + if sandbox_mode_rank(requested) > sandbox_mode_rank(parent_mode) { + drop(permit); + return Err(SubagentManagerError::SandboxOverrideForbidden { + requested, + parent: parent_mode, + }); + } + let policy = sandbox_policy_for_mode(requested, &parent_policy); + config.sandbox_policy = policy; + } + let cancel_token = CancellationToken::new(); + let child = match run_codex_conversation_interactive( + config, + Arc::clone(&session.services.auth_manager), + Arc::clone(&session), + Arc::clone(&turn), + cancel_token.clone(), + Some(session_id), + initial_history, + SubAgentSource::Other("subagent_orchestrator".into()), + ) + .await + { + Ok(child) => child, + Err(err) => { + drop(permit); + return Err(SubagentManagerError::LaunchFailed(err.to_string())); + } + }; + + let entry = Arc::new(ManagedSubagent::new(child, cancel_token, permit)); + + { + let mut runs = self.runs.write().await; + runs.insert(session_id, Arc::clone(&entry)); + } + + let manager = self.clone(); + let runtime = Arc::clone(&entry); + tokio::spawn(async move { + manager.pump_events(session_id, runtime).await; + }); + + let pending_ops_manager = self.clone(); + let pending_ops_runtime = Arc::clone(&entry); + tokio::spawn(async move { + pending_ops_manager + .run_pending_ops(session_id, pending_ops_runtime) + .await; + }); + + Ok(entry) + } + + async fn pump_events(&self, session_id: ConversationId, runtime: Arc) { + let cancel = runtime.cancellation_token(); + loop { + tokio::select! { + _ = cancel.cancelled() => { + // Cancellation is triggered only after finalize_terminal has already + // updated registry state and shut the runtime down. + break; + } + next = runtime.codex.next_event() => { + match next { + Ok(event) => { + runtime.record_event(&event).await; + match &event.msg { + EventMsg::AgentReasoningDelta(delta) => { + if !runtime.append_reasoning_delta(&delta.delta).await { + continue; + } + if let Some(header) = runtime.reasoning_header().await { + self + .update_reasoning_header_and_emit( + &session_id, + header, + ) + .await; + } + } + EventMsg::AgentReasoning(reasoning) => { + if runtime.reasoning_header().await.is_none() + && let Some(header) = + extract_first_bold(&reasoning.text) + { + runtime.set_reasoning_header(header.clone()).await; + self + .update_reasoning_header_and_emit( + &session_id, + header, + ) + .await; + } + } + EventMsg::TaskComplete(ev) => { + runtime + .set_completion(SubagentCompletion::Completed { + last_message: ev.last_agent_message.clone(), + }) + .await; + + // Treat normal completion as an implicit + // subagent_await: drain any pending inbox + // messages, update terminal status, and + // inject synthetic tool calls / user + // messages into the parent and child + // histories so callers do not need to + // issue an explicit await. + if let Ok(result) = self + .await_inbox_and_completion( + &session_id, + Some(Duration::from_millis(0)), + ) + .await + { + self + .deliver_inbox_to_threads_at_yield(&result) + .await; + + if let Some(completion) = result.completion.clone() { + let status = status_from_completion(&completion); + self + .finalize_terminal( + &session_id, + Arc::clone(&runtime), + completion, + status, + ) + .await; + } + } + } + EventMsg::TurnAborted(ev) => { + // Interrupted turn: treat as a + // cancellation, surface any pending inbox + // messages via a synthetic await, then + // finalize the runtime. + runtime + .set_completion(SubagentCompletion::Canceled { + reason: ev.reason.clone(), + }) + .await; + if let Ok(result) = self + .await_inbox_and_completion( + &session_id, + Some(Duration::from_millis(0)), + ) + .await + { + self + .deliver_inbox_to_threads_at_yield(&result) + .await; + } + self + .finalize_terminal( + &session_id, + Arc::clone(&runtime), + SubagentCompletion::Canceled { + reason: ev.reason.clone(), + }, + SubagentStatus::Canceled, + ) + .await; + break; + } + EventMsg::StreamError(ev) => { + runtime + .set_completion(SubagentCompletion::Failed { + message: ev.message.clone(), + }) + .await; + if let Ok(result) = self + .await_inbox_and_completion( + &session_id, + Some(Duration::from_millis(0)), + ) + .await + { + self + .deliver_inbox_to_threads_at_yield(&result) + .await; + } + self + .finalize_terminal( + &session_id, + Arc::clone(&runtime), + SubagentCompletion::Failed { + message: ev.message.clone(), + }, + SubagentStatus::Failed, + ) + .await; + break; + } + EventMsg::Error(ev) => { + runtime + .set_completion(SubagentCompletion::Failed { + message: ev.message.clone(), + }) + .await; + if let Ok(result) = self + .await_inbox_and_completion( + &session_id, + Some(Duration::from_millis(0)), + ) + .await + { + self + .deliver_inbox_to_threads_at_yield(&result) + .await; + } + self + .finalize_terminal( + &session_id, + Arc::clone(&runtime), + SubagentCompletion::Failed { + message: ev.message.clone(), + }, + SubagentStatus::Failed, + ) + .await; + break; + } + _ => {} + } + } + Err(err) => { + self + .finalize_terminal( + &session_id, + Arc::clone(&runtime), + SubagentCompletion::Failed { + message: err.to_string(), + }, + SubagentStatus::Failed, + ) + .await; + break; + } + } + } + } + } + // Runtime is kept alive after completion so messages can resume; no auto-removal here. + } + + async fn run_pending_ops(&self, session_id: ConversationId, runtime: Arc) { + let cancel = runtime.cancellation_token(); + let notify = runtime.pending_ops_notifier(); + loop { + while let Some((message, counts)) = runtime.dequeue_message().await { + let PendingMessage { prompt, interrupt } = message; + self.update_inbox_counts_and_emit(&session_id, counts.0, counts.1) + .await; + if interrupt { + runtime.interrupt().await; + } + if let Some(prompt) = prompt { + match runtime.submit_prompt(&prompt).await { + Ok(true) => { + self.update_status_and_emit(&session_id, SubagentStatus::Running) + .await; + } + Ok(false) => { + self.update_status_and_emit(&session_id, SubagentStatus::Ready) + .await; + } + Err(err) => { + self.finalize_terminal( + &session_id, + Arc::clone(&runtime), + SubagentCompletion::Failed { + message: err.to_string(), + }, + SubagentStatus::Failed, + ) + .await; + return; + } + } + } else if interrupt { + self.update_status_and_emit(&session_id, SubagentStatus::Ready) + .await; + } + } + + tokio::select! { + _ = cancel.cancelled() => break, + _ = notify.notified() => continue, + } + } + } + + async fn finalize_terminal( + &self, + session_id: &ConversationId, + runtime: Arc, + completion: SubagentCompletion, + status: SubagentStatus, + ) { + let completion_clone = completion.clone(); + runtime.set_completion(completion.clone()).await; + self.update_status_and_emit(session_id, status).await; + { + let mut completions = self.completions.write().await; + completions.insert(*session_id, completion_clone); + } + let log_snapshot = runtime.snapshot_logs().await; + { + let mut logs = self.completed_logs.write().await; + logs.insert(*session_id, log_snapshot); + } + let inbox_snapshot = runtime.snapshot_inbox().await; + { + let mut inbox = self.completed_inbox.write().await; + inbox.insert(*session_id, inbox_snapshot); + } + // Do NOT shut down or remove the runtime; keep it alive so further messages + // can be processed unless explicitly pruned or canceled. + + // Surface completion to the parent as a logical inbox message, so from + // the parent's perspective a completion is equivalent to a + // subagent_send_message targeting the parent agent id. + self.send_completion_to_parent(session_id, completion).await; + } + + async fn remove_runtime_entry( + &self, + session_id: &ConversationId, + ) -> Option> { + let mut runs = self.runs.write().await; + runs.remove(session_id) + } + + async fn handle_launch_failure( + &self, + session_id: ConversationId, + runtime: Arc, + err: CodexErr, + ) { + self.finalize_terminal( + &session_id, + runtime, + SubagentCompletion::Failed { + message: err.to_string(), + }, + SubagentStatus::Failed, + ) + .await; + } + + async fn send_completion_to_parent( + &self, + session_id: &ConversationId, + completion: SubagentCompletion, + ) { + let Some(metadata) = self.registry.get(session_id).await else { + return; + }; + + let Some(parent_session_id) = metadata.parent_session_id else { + return; + }; + + // If the parent is the root agent (id 0), enqueue into the root inbox. + if metadata.parent_agent_id == Some(ROOT_AGENT_ID) { + self.enqueue_root_inbox_completion( + &parent_session_id, + session_id, + completion, + metadata.clone(), + ) + .await; + } else if let Some(parent_agent_id) = metadata.parent_agent_id { + let completion_prompt = match &completion { + SubagentCompletion::Completed { last_message } => last_message + .clone() + .unwrap_or_else(|| "subagent completed".to_string()), + SubagentCompletion::Failed { message } => { + format!("subagent failed: {message}") + } + SubagentCompletion::Canceled { reason } => { + format!("subagent canceled: {reason:?}") + } + }; + + // Otherwise, treat the parent as another subagent and enqueue a + // logical message into its inbox. + let _ = self + .send_message(SendMessageRequest { + session_id: parent_session_id, + label: None, + summary: None, + prompt: Some(completion_prompt), + agent_id: parent_agent_id, + sender_agent_id: metadata.agent_id, + interrupt: false, + }) + .await; + } + } +} + +#[derive(Debug, thiserror::Error)] +pub enum SubagentManagerError { + #[error("subagent session not found")] + NotFound, + #[error("agent id mismatch for session {session_id} (agent_id {agent_id})")] + AgentIdMismatch { + session_id: ConversationId, + agent_id: AgentId, + }, + #[error("failed to launch subagent: {0}")] + LaunchFailed(String), + #[error("active subagent limit ({limit}) reached")] + LimitReached { limit: usize }, + #[error("timed out waiting {timeout_ms} ms for agent_id {agent_id}")] + AwaitTimedOut { + session_id: ConversationId, + agent_id: AgentId, + timeout_ms: u64, + }, + #[error("invalid prune request: {0}")] + InvalidPruneRequest(String), + #[error( + "sandbox override {requested:?} not permitted because parent session runs in {parent:?}" + )] + SandboxOverrideForbidden { + requested: SandboxMode, + parent: SandboxMode, + }, +} + +#[derive(Debug, Clone)] +pub struct SpawnRequest { + pub prompt: String, + pub label: Option, + pub summary: Option, + pub sandbox_mode: Option, + pub model: Option, +} + +#[derive(Debug, Clone)] +pub struct ForkRequest { + pub parent_session_id: ConversationId, + pub initial_message_count: usize, + pub label: Option, + pub summary: Option, + pub call_id: String, + pub arguments: String, + pub prompt: Option, + pub sandbox_mode: Option, + pub model: Option, +} + +#[derive(Debug, Clone)] +pub struct SendMessageRequest { + pub session_id: ConversationId, + pub label: Option, + pub summary: Option, + pub prompt: Option, + pub agent_id: AgentId, + /// Agent id of the sender; this is used for inbox + /// attribution so awaiters can see who sent each + /// message. + pub sender_agent_id: AgentId, + pub interrupt: bool, +} + +#[derive(Clone, Debug, Serialize)] +pub struct InboxMessage { + pub sender_agent_id: AgentId, + pub recipient_agent_id: AgentId, + pub interrupt: bool, + pub prompt: Option, + pub timestamp_ms: i64, +} + +#[derive(Clone, Debug)] +struct PendingMessage { + prompt: Option, + interrupt: bool, +} + +#[derive(Default)] +struct PendingOpsQueues { + regular: VecDeque, + interrupts: VecDeque, +} + +impl PendingOpsQueues { + fn counts(&self) -> (usize, usize) { + (self.regular.len(), self.interrupts.len()) + } + + fn push(&mut self, message: PendingMessage) { + if message.interrupt { + self.interrupts.push_back(message); + } else { + self.regular.push_back(message); + } + } + + fn pop(&mut self) -> Option { + if let Some(msg) = self.interrupts.pop_front() { + return Some(msg); + } + self.regular.pop_front() + } +} + +#[derive(Clone)] +struct SubagentEmitter { + session: Arc, + turn: Arc, +} + +struct ManagedSubagent { + codex: Codex, + cancel_token: CancellationToken, + logs: Mutex>, + completion_tx: watch::Sender>, + completion_rx: watch::Receiver>, + reasoning_buffer: Mutex, + reasoning_header: Mutex>, + inbox: Mutex>, + inbox_notify: Arc, + pending_ops: Mutex, + pending_ops_notify: Arc, + _permit: Mutex>, +} + +impl ManagedSubagent { + fn new(codex: Codex, cancel_token: CancellationToken, permit: OwnedSemaphorePermit) -> Self { + let (completion_tx, completion_rx) = watch::channel(None); + Self { + codex, + cancel_token, + logs: Mutex::new(VecDeque::with_capacity(LOG_CAPACITY)), + completion_tx, + completion_rx, + reasoning_buffer: Mutex::new(String::new()), + reasoning_header: Mutex::new(None), + inbox: Mutex::new(VecDeque::new()), + inbox_notify: Arc::new(Notify::new()), + pending_ops: Mutex::new(PendingOpsQueues::default()), + pending_ops_notify: Arc::new(Notify::new()), + _permit: Mutex::new(Some(permit)), + } + } + + async fn submit_prompt(&self, prompt: &str) -> Result { + if prompt.trim().is_empty() { + return Ok(false); + } + let items = vec![UserInput::Text { + text: prompt.to_string(), + }]; + self.codex + .submit(codex_protocol::protocol::Op::UserInput { items }) + .await?; + Ok(true) + } + + async fn enqueue_message(&self, message: PendingMessage) -> (usize, usize) { + let mut guard = self.pending_ops.lock().await; + guard.push(message); + let counts = guard.counts(); + self.pending_ops_notify.notify_one(); + counts + } + + async fn dequeue_message(&self) -> Option<(PendingMessage, (usize, usize))> { + let mut guard = self.pending_ops.lock().await; + guard.pop().map(|msg| (msg, guard.counts())) + } + + fn pending_ops_notifier(&self) -> Arc { + Arc::clone(&self.pending_ops_notify) + } + + async fn enqueue_inbox_message(&self, message: InboxMessage) -> usize { + let mut guard = self.inbox.lock().await; + guard.push_back(message); + let len = guard.len(); + self.inbox_notify.notify_one(); + len + } + + async fn drain_inbox(&self) -> Vec { + let mut guard = self.inbox.lock().await; + guard.drain(..).collect() + } + + async fn snapshot_inbox(&self) -> Vec { + let guard = self.inbox.lock().await; + guard.iter().cloned().collect() + } + + fn inbox_notifier(&self) -> Arc { + Arc::clone(&self.inbox_notify) + } + + async fn interrupt(&self) { + let _ = self + .codex + .submit(codex_protocol::protocol::Op::Interrupt) + .await; + } + + fn cancellation_token(&self) -> CancellationToken { + self.cancel_token.clone() + } + + async fn shutdown(&self) { + let _ = self + .codex + .submit(codex_protocol::protocol::Op::Shutdown {}) + .await; + self.cancel_token.cancel(); + } + + async fn record_event(&self, event: &Event) { + let mut logs = self.logs.lock().await; + if logs.len() >= LOG_CAPACITY { + logs.pop_front(); + } + logs.push_back(LoggedEvent::new(event.clone())); + } + + async fn set_completion(&self, completion: SubagentCompletion) { + let _ = self.completion_tx.send_replace(Some(completion)); + } + + fn clear_completion(&self) { + let _ = self.completion_tx.send_replace(None); + } + + fn completion_receiver(&self) -> watch::Receiver> { + self.completion_rx.clone() + } + + async fn snapshot_logs(&self) -> Vec { + let logs = self.logs.lock().await; + logs.iter().cloned().collect() + } + + async fn reasoning_header(&self) -> Option { + self.reasoning_header.lock().await.clone() + } + + async fn set_reasoning_header(&self, header: String) { + let mut guard = self.reasoning_header.lock().await; + *guard = Some(header); + } + + async fn append_reasoning_delta(&self, delta: &str) -> bool { + { + let guard = self.reasoning_header.lock().await; + if guard.is_some() { + return true; + } + } + let mut buf = self.reasoning_buffer.lock().await; + buf.push_str(delta); + if let Some(header) = extract_first_bold(&buf) { + drop(buf); + self.set_reasoning_header(header).await; + return true; + } + false + } +} + +#[derive(Clone)] +struct LoggedEvent { + timestamp: SystemTime, + event: Event, +} + +impl LoggedEvent { + fn new(event: Event) -> Self { + Self { + timestamp: SystemTime::now(), + event, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct LogEntry { + pub timestamp_ms: i64, + pub event: Event, +} + +impl LogEntry { + fn from_logged(src: &LoggedEvent) -> Self { + Self { + timestamp_ms: unix_time_millis(src.timestamp), + event: src.event.clone(), + } + } +} + +fn unix_time_millis(time: SystemTime) -> i64 { + match time.duration_since(UNIX_EPOCH) { + Ok(duration) => duration.as_millis() as i64, + Err(err) => -(err.duration().as_millis() as i64), + } +} + +fn extract_first_bold(s: &str) -> Option { + let bytes = s.as_bytes(); + let mut i = 0usize; + while i + 1 < bytes.len() { + if bytes[i] == b'*' && bytes[i + 1] == b'*' { + let start = i + 2; + let mut j = start; + while j + 1 < bytes.len() { + if bytes[j] == b'*' && bytes[j + 1] == b'*' { + let inner = &s[start..j]; + let trimmed = inner.trim(); + if !trimmed.is_empty() { + return Some(trimmed.to_string()); + } else { + return None; + } + } + j += 1; + } + break; + } + i += 1; + } + None +} + +fn sandbox_mode_from_policy(policy: &SandboxPolicy) -> SandboxMode { + match policy { + SandboxPolicy::DangerFullAccess => SandboxMode::DangerFullAccess, + SandboxPolicy::WorkspaceWrite { .. } => SandboxMode::WorkspaceWrite, + SandboxPolicy::ReadOnly => SandboxMode::ReadOnly, + } +} + +fn sandbox_mode_rank(mode: SandboxMode) -> u8 { + match mode { + SandboxMode::DangerFullAccess => 3, + SandboxMode::WorkspaceWrite => 2, + SandboxMode::ReadOnly => 1, + } +} + +fn sandbox_policy_for_mode(requested: SandboxMode, parent_policy: &SandboxPolicy) -> SandboxPolicy { + match requested { + SandboxMode::ReadOnly => SandboxPolicy::new_read_only_policy(), + SandboxMode::WorkspaceWrite => match parent_policy { + SandboxPolicy::WorkspaceWrite { .. } => parent_policy.clone(), + _ => SandboxPolicy::new_workspace_write_policy(), + }, + SandboxMode::DangerFullAccess => SandboxPolicy::DangerFullAccess, + } +} + +fn to_subagent_summary(metadata: &SubagentMetadata) -> SubagentSummary { + SubagentSummary { + agent_id: metadata.agent_id, + parent_agent_id: metadata.parent_agent_id, + session_id: metadata.session_id, + parent_session_id: metadata.parent_session_id, + origin: metadata.origin.into(), + status: metadata.status.into(), + label: metadata.label.clone(), + summary: metadata.summary.clone(), + reasoning_header: metadata.reasoning_header.clone(), + started_at_ms: metadata.created_at_ms, + pending_messages: metadata.pending_messages, + pending_interrupts: metadata.pending_interrupts, + } +} + +impl From for SubagentLifecycleOrigin { + fn from(value: SubagentOrigin) -> Self { + match value { + SubagentOrigin::Spawn => SubagentLifecycleOrigin::Spawn, + SubagentOrigin::Fork => SubagentLifecycleOrigin::Fork, + SubagentOrigin::SendMessage => SubagentLifecycleOrigin::SendMessage, + } + } +} + +impl From for SubagentLifecycleStatus { + fn from(value: SubagentStatus) -> Self { + match value { + SubagentStatus::Queued => SubagentLifecycleStatus::Queued, + SubagentStatus::Running => SubagentLifecycleStatus::Running, + SubagentStatus::Ready => SubagentLifecycleStatus::Ready, + SubagentStatus::Idle => SubagentLifecycleStatus::Idle, + SubagentStatus::Failed => SubagentLifecycleStatus::Failed, + SubagentStatus::Canceled => SubagentLifecycleStatus::Canceled, + } + } +} + +#[derive(Clone, Debug, Serialize)] +pub enum SubagentCompletion { + Completed { last_message: Option }, + Canceled { reason: TurnAbortReason }, + Failed { message: String }, +} + +#[derive(Clone, Debug, Serialize)] +pub struct AwaitResult { + pub metadata: SubagentMetadata, + pub completion: SubagentCompletion, +} + +#[derive(Clone, Debug, Serialize)] +pub struct AwaitInboxResult { + pub metadata: SubagentMetadata, + pub completion: Option, + pub messages: Vec, +} + +#[derive(Clone, Debug)] +pub struct PruneRequest { + pub session_ids: Option>, + pub all: bool, + pub completed_only: bool, +} + +#[derive(Clone, Debug, Serialize)] +pub struct PruneErrorEntry { + pub session_id: ConversationId, + pub message: String, +} + +#[derive(Clone, Debug, Default, Serialize)] +pub struct PruneReport { + pub pruned: Vec, + pub skipped_active: Vec, + pub unknown: Vec, + pub errors: Vec, +} + +async fn build_fork_history(session: Arc) -> InitialHistory { + let mut history = session.clone_history().await; + let items = history.get_history_for_prompt(); + if items.is_empty() { + InitialHistory::New + } else { + let rollout = items + .into_iter() + .map(RolloutItem::ResponseItem) + .collect::>(); + InitialHistory::Forked(rollout) + } +} + +fn remove_call_items(items: &mut Vec, call_id: &str) { + items.retain(|item| { + !matches!( + item, + RolloutItem::ResponseItem(ResponseItem::FunctionCall { call_id: cid, .. }) + if cid == call_id + ) && !matches!( + item, + RolloutItem::ResponseItem(ResponseItem::FunctionCallOutput { call_id: cid, .. }) + if cid == call_id + ) + }); +} + +fn current_completion( + receiver: &watch::Receiver>, +) -> Option { + receiver.borrow().clone() +} + +fn status_from_completion(completion: &SubagentCompletion) -> SubagentStatus { + match completion { + SubagentCompletion::Completed { .. } => SubagentStatus::Idle, + SubagentCompletion::Failed { .. } => SubagentStatus::Failed, + SubagentCompletion::Canceled { .. } => SubagentStatus::Canceled, + } +} + +fn is_terminal_status(status: SubagentStatus) -> bool { + matches!( + status, + SubagentStatus::Idle | SubagentStatus::Failed | SubagentStatus::Canceled + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::codex::SUBMISSION_CHANNEL_CAPACITY; + use async_channel::bounded; + use codex_protocol::protocol::TurnAbortReason; + + use std::time::Duration; + + async fn setup_await_fixture() -> (Arc, ConversationId, Arc) { + let registry = Arc::new(SubagentRegistry::new()); + let manager = Arc::new(SubagentManager::new( + Arc::clone(®istry), + 2, + false, + false, + false, + )); + let session_id = ConversationId::new(); + registry + .register_spawn( + session_id, + None, + Some(ROOT_AGENT_ID), + 1, + 0, + Some("child".to_string()), + None, + ) + .await; + + let permit = manager + .permits + .clone() + .acquire_owned() + .await + .expect("permit"); + let (tx_sub, _rx_sub) = bounded(SUBMISSION_CHANNEL_CAPACITY); + let (_tx_event, rx_event) = bounded(SUBMISSION_CHANNEL_CAPACITY); + let codex = Codex { + next_id: AtomicU64::new(1), + tx_sub, + rx_event, + conversation_id: session_id, + }; + let runtime = Arc::new(ManagedSubagent::new( + codex, + CancellationToken::new(), + permit, + )); + manager + .runs + .write() + .await + .insert(session_id, Arc::clone(&runtime)); + + (manager, session_id, runtime) + } + + #[tokio::test] + async fn await_inbox_unblocks_on_message() { + let (manager, session_id, runtime) = setup_await_fixture().await; + let waiter = tokio::spawn({ + let manager = Arc::clone(&manager); + async move { + manager + .await_inbox_and_completion(&session_id, Some(Duration::from_secs(30))) + .await + .expect("await result") + } + }); + + tokio::time::sleep(Duration::from_millis(10)).await; + runtime + .enqueue_inbox_message(InboxMessage { + sender_agent_id: 1, + recipient_agent_id: ROOT_AGENT_ID, + interrupt: false, + prompt: Some("hello".to_string()), + timestamp_ms: 1, + }) + .await; + + let result = waiter.await.expect("join awaiter"); + assert!(result.completion.is_none()); + assert_eq!(result.messages.len(), 1); + assert_eq!(result.messages[0].prompt.as_deref(), Some("hello")); + } + + #[tokio::test] + async fn await_inbox_unblocks_on_completion() { + let (manager, session_id, runtime) = setup_await_fixture().await; + let waiter = tokio::spawn({ + let manager = Arc::clone(&manager); + async move { + manager + .await_inbox_and_completion(&session_id, None) + .await + .expect("await result") + } + }); + + tokio::time::sleep(Duration::from_millis(10)).await; + runtime + .completion_tx + .send_replace(Some(SubagentCompletion::Completed { + last_message: Some("done".to_string()), + })); + + let result = waiter.await.expect("join awaiter"); + assert!(result.messages.is_empty()); + assert!(matches!( + result.completion, + Some(SubagentCompletion::Completed { .. }) + )); + } + + #[tokio::test] + async fn await_completion_marks_status_completed() { + let registry = Arc::new(SubagentRegistry::new()); + let manager = SubagentManager::new(Arc::clone(®istry), 1, false, false, false); + let session_id = ConversationId::new(); + registry + .register_spawn(session_id, None, None, 1, 0, None, None) + .await; + + { + let mut completions = manager.completions.write().await; + completions.insert( + session_id, + SubagentCompletion::Completed { + last_message: Some("done".to_string()), + }, + ); + } + + let result = manager + .await_completion(&session_id, None) + .await + .expect("await result"); + assert_eq!(result.metadata.status, SubagentStatus::Idle); + } + + #[tokio::test] + async fn await_completion_preserves_failed_and_canceled() { + let registry = Arc::new(SubagentRegistry::new()); + let manager = SubagentManager::new(Arc::clone(®istry), 1, false, false, false); + let session_id = ConversationId::new(); + registry + .register_spawn(session_id, None, None, 1, 0, None, None) + .await; + + for completion in [ + SubagentCompletion::Failed { + message: "boom".to_string(), + }, + SubagentCompletion::Canceled { + reason: TurnAbortReason::Interrupted, + }, + ] { + { + let mut completions = manager.completions.write().await; + completions.insert(session_id, completion.clone()); + } + + let result = manager + .await_completion(&session_id, None) + .await + .expect("await result"); + + let expected_status = status_from_completion(&completion); + assert_eq!(result.metadata.status, expected_status); + assert_eq!(status_from_completion(&completion), expected_status); + } + } + + #[tokio::test] + async fn cancel_without_runtime_marks_status_canceled() { + let registry = Arc::new(SubagentRegistry::new()); + let manager = SubagentManager::new(Arc::clone(®istry), 1, false, false, false); + let session_id = ConversationId::new(); + registry + .register_spawn( + session_id, + Some(ConversationId::new()), + Some(1), + 2, + 0, + None, + None, + ) + .await; + + let metadata = manager.cancel(session_id).await.expect("cancel result"); + assert_eq!(metadata.status, SubagentStatus::Canceled); + + let stored = registry.get(&session_id).await.expect("metadata"); + assert_eq!(stored.status, SubagentStatus::Canceled); + + let completions = manager.completions.read().await; + assert!(matches!( + completions.get(&session_id), + Some(SubagentCompletion::Canceled { .. }) + )); + } + + #[tokio::test] + async fn root_inbox_carries_completion_payload() { + let registry = Arc::new(SubagentRegistry::new()); + let manager = SubagentManager::new(Arc::clone(®istry), 4, false, true, false); + let root_session = ConversationId::new(); + let child_session = ConversationId::new(); + + registry + .register_spawn( + child_session, + Some(root_session), + Some(ROOT_AGENT_ID), + 1, + 0, + Some("child".to_string()), + None, + ) + .await; + + manager + .send_completion_to_parent( + &child_session, + SubagentCompletion::Completed { + last_message: Some("done".to_string()), + }, + ) + .await; + + let items = manager.drain_root_inbox_to_items(&root_session).await; + assert_eq!(items.len(), 2); + + let content = items + .iter() + .find_map(|item| match item { + ResponseItem::FunctionCallOutput { output, .. } => Some(output.content.clone()), + _ => None, + }) + .expect("function call output"); + let payload: serde_json::Value = serde_json::from_str(&content).expect("valid json"); + assert_eq!(payload["completion_status"], "completed"); + assert_eq!( + payload["completion"]["Completed"]["last_message"], + serde_json::Value::String("done".to_string()) + ); + assert_eq!(payload["messages"], serde_json::Value::Array(Vec::new())); + } + + #[tokio::test] + async fn root_inbox_preserves_fifo_across_senders() { + let registry = Arc::new(SubagentRegistry::new()); + let manager = SubagentManager::new(Arc::clone(®istry), 4, false, true, false); + let root_session = ConversationId::new(); + let child_a = ConversationId::new(); + let child_b = ConversationId::new(); + + registry + .register_spawn( + child_a, + Some(root_session), + Some(ROOT_AGENT_ID), + 1, + 0, + Some("alpha".to_string()), + None, + ) + .await; + registry + .register_spawn( + child_b, + Some(root_session), + Some(ROOT_AGENT_ID), + 2, + 0, + Some("beta".to_string()), + None, + ) + .await; + + manager + .enqueue_root_inbox_message( + &root_session, + &child_b, + InboxMessage { + sender_agent_id: 2, + recipient_agent_id: ROOT_AGENT_ID, + interrupt: false, + prompt: Some("m2-first".to_string()), + timestamp_ms: 5, + }, + ) + .await; + manager + .enqueue_root_inbox_message( + &root_session, + &child_a, + InboxMessage { + sender_agent_id: 1, + recipient_agent_id: ROOT_AGENT_ID, + interrupt: false, + prompt: Some("m1-only".to_string()), + timestamp_ms: 10, + }, + ) + .await; + manager + .enqueue_root_inbox_message( + &root_session, + &child_b, + InboxMessage { + sender_agent_id: 2, + recipient_agent_id: ROOT_AGENT_ID, + interrupt: false, + prompt: Some("m2-late".to_string()), + timestamp_ms: 15, + }, + ) + .await; + + let items = manager.drain_root_inbox_to_items(&root_session).await; + assert_eq!(items.len(), 4); + + let mut order = Vec::new(); + for chunk in items.chunks(2) { + if let [ + ResponseItem::FunctionCall { arguments: _, .. }, + ResponseItem::FunctionCallOutput { output, .. }, + ] = chunk + { + let payload: serde_json::Value = + serde_json::from_str(&output.content).expect("payload json"); + let agent_id = payload["metadata"]["agent_id"].as_i64().expect("agent id"); + order.push(agent_id); + let prompts = payload["messages"] + .as_array() + .expect("messages array") + .iter() + .map(|entry| entry["prompt"].as_str().unwrap().to_string()) + .collect::>(); + if agent_id == 2 { + assert_eq!(prompts, vec!["m2-first".to_string(), "m2-late".to_string()]); + } else { + assert_eq!(prompts, vec!["m1-only".to_string()]); + } + } else { + panic!("unexpected chunk layout"); + } + } + + assert_eq!(order, vec![2, 1]); + } +} diff --git a/codex-rs/core/src/subagents/mod.rs b/codex-rs/core/src/subagents/mod.rs new file mode 100644 index 0000000000..29b8b2d20a --- /dev/null +++ b/codex-rs/core/src/subagents/mod.rs @@ -0,0 +1,21 @@ +mod manager; +mod registry; + +pub use manager::AwaitInboxResult; +pub use manager::AwaitResult; +pub use manager::ForkRequest; +pub use manager::InboxMessage; +pub use manager::LogEntry; +pub use manager::PruneErrorEntry; +pub use manager::PruneReport; +pub use manager::PruneRequest; +pub use manager::SendMessageRequest; +pub use manager::SpawnRequest; +pub use manager::SubagentCompletion; +pub use manager::SubagentManager; +pub use manager::SubagentManagerError; +pub use manager::WatchdogAction; +pub use registry::SubagentMetadata; +pub use registry::SubagentOrigin; +pub use registry::SubagentRegistry; +pub use registry::SubagentStatus; diff --git a/codex-rs/core/src/subagents/registry.rs b/codex-rs/core/src/subagents/registry.rs new file mode 100644 index 0000000000..591e86d51e --- /dev/null +++ b/codex-rs/core/src/subagents/registry.rs @@ -0,0 +1,335 @@ +use std::collections::HashMap; +use std::sync::Arc; +use std::time::SystemTime; +use std::time::UNIX_EPOCH; + +use codex_protocol::AgentId; +use codex_protocol::ConversationId; +use codex_protocol::protocol::SubagentLifecycleOrigin; +use codex_protocol::protocol::SubagentLifecycleStatus; +use serde::Serialize; +use tokio::sync::RwLock; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum SubagentOrigin { + Spawn, + Fork, + SendMessage, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum SubagentStatus { + Queued, + Running, + Ready, + Idle, + Failed, + Canceled, +} + +#[derive(Clone, Debug, Serialize)] +pub struct SubagentMetadata { + pub agent_id: AgentId, + pub parent_agent_id: Option, + pub session_id: ConversationId, + pub parent_session_id: Option, + pub origin: SubagentOrigin, + pub initial_message_count: usize, + pub status: SubagentStatus, + #[serde(skip_serializing)] + pub created_at: SystemTime, + #[serde(skip_serializing)] + pub created_at_ms: i64, + #[serde(skip_serializing)] + pub session_key: String, + pub label: Option, + pub summary: Option, + pub reasoning_header: Option, + pub pending_messages: usize, + pub pending_interrupts: usize, +} + +#[derive(Clone, Default)] +pub struct SubagentRegistry { + inner: Arc>>, +} + +impl SubagentMetadata { + #[allow(clippy::too_many_arguments)] + fn new( + session_id: ConversationId, + parent_session_id: Option, + agent_id: AgentId, + parent_agent_id: Option, + origin: SubagentOrigin, + initial_message_count: usize, + label: Option, + summary: Option, + ) -> Self { + let created_at = SystemTime::now(); + Self { + agent_id, + parent_agent_id, + session_id, + parent_session_id, + origin, + initial_message_count, + status: SubagentStatus::Queued, + created_at, + created_at_ms: unix_time_millis(created_at), + session_key: session_id.to_string(), + label, + summary, + reasoning_header: None, + pending_messages: 0, + pending_interrupts: 0, + } + } +} + +impl SubagentMetadata { + pub fn from_summary(summary: &codex_protocol::protocol::SubagentSummary) -> Self { + let created_at = if summary.started_at_ms >= 0 { + std::time::UNIX_EPOCH + std::time::Duration::from_millis(summary.started_at_ms as u64) + } else { + std::time::UNIX_EPOCH + - std::time::Duration::from_millis(summary.started_at_ms.unsigned_abs()) + }; + SubagentMetadata { + agent_id: summary.agent_id, + parent_agent_id: summary.parent_agent_id, + session_id: summary.session_id, + parent_session_id: summary.parent_session_id, + origin: SubagentOrigin::from(summary.origin), + initial_message_count: 0, + status: SubagentStatus::from(summary.status), + created_at, + created_at_ms: summary.started_at_ms, + session_key: summary.session_id.to_string(), + label: summary.label.clone(), + summary: summary.summary.clone(), + reasoning_header: summary.reasoning_header.clone(), + pending_messages: summary.pending_messages, + pending_interrupts: summary.pending_interrupts, + } + } +} + +impl From for SubagentStatus { + fn from(status: SubagentLifecycleStatus) -> Self { + match status { + SubagentLifecycleStatus::Queued => SubagentStatus::Queued, + SubagentLifecycleStatus::Running => SubagentStatus::Running, + SubagentLifecycleStatus::Ready => SubagentStatus::Ready, + SubagentLifecycleStatus::Idle => SubagentStatus::Idle, + SubagentLifecycleStatus::Failed => SubagentStatus::Failed, + SubagentLifecycleStatus::Canceled => SubagentStatus::Canceled, + } + } +} + +impl From for SubagentOrigin { + fn from(origin: SubagentLifecycleOrigin) -> Self { + match origin { + SubagentLifecycleOrigin::Spawn => SubagentOrigin::Spawn, + SubagentLifecycleOrigin::Fork => SubagentOrigin::Fork, + SubagentLifecycleOrigin::SendMessage => SubagentOrigin::SendMessage, + } + } +} + +impl SubagentRegistry { + pub fn new() -> Self { + Self::default() + } + + #[allow(clippy::too_many_arguments)] + pub async fn register_spawn( + &self, + session_id: ConversationId, + parent_session_id: Option, + parent_agent_id: Option, + agent_id: AgentId, + initial_message_count: usize, + label: Option, + summary: Option, + ) -> SubagentMetadata { + let metadata = SubagentMetadata::new( + session_id, + parent_session_id, + agent_id, + parent_agent_id, + SubagentOrigin::Spawn, + initial_message_count, + label, + summary, + ); + self.insert_if_absent(metadata).await + } + + #[allow(clippy::too_many_arguments)] + pub async fn register_fork( + &self, + session_id: ConversationId, + parent_session_id: ConversationId, + parent_agent_id: Option, + agent_id: AgentId, + initial_message_count: usize, + label: Option, + summary: Option, + ) -> SubagentMetadata { + let metadata = SubagentMetadata::new( + session_id, + Some(parent_session_id), + agent_id, + parent_agent_id, + SubagentOrigin::Fork, + initial_message_count, + label, + summary, + ); + self.insert_if_absent(metadata).await + } + + #[allow(clippy::too_many_arguments)] + pub async fn register_resume( + &self, + session_id: ConversationId, + parent_session_id: ConversationId, + parent_agent_id: Option, + agent_id: AgentId, + initial_message_count: usize, + label: Option, + summary: Option, + ) -> SubagentMetadata { + let metadata = SubagentMetadata::new( + session_id, + Some(parent_session_id), + agent_id, + parent_agent_id, + SubagentOrigin::SendMessage, + initial_message_count, + label, + summary, + ); + self.insert_if_absent(metadata).await + } + + pub async fn update_status( + &self, + session_id: &ConversationId, + status: SubagentStatus, + ) -> Option { + let mut guard = self.inner.write().await; + if let Some(entry) = guard.get_mut(session_id) { + entry.status = status; + return Some(entry.clone()); + } + None + } + + pub async fn update_reasoning_header( + &self, + session_id: &ConversationId, + header: String, + ) -> Option { + let mut guard = self.inner.write().await; + if let Some(entry) = guard.get_mut(session_id) { + entry.reasoning_header = Some(header); + return Some(entry.clone()); + } + None + } + + pub async fn get(&self, session_id: &ConversationId) -> Option { + let guard = self.inner.read().await; + guard.get(session_id).cloned() + } + + pub async fn update_label_and_summary( + &self, + session_id: &ConversationId, + label: Option, + summary: Option, + ) -> Option { + let mut guard = self.inner.write().await; + if let Some(entry) = guard.get_mut(session_id) { + entry.label = label; + entry.summary = summary; + return Some(entry.clone()); + } + None + } + + pub async fn update_inbox_counts( + &self, + session_id: &ConversationId, + pending_messages: usize, + pending_interrupts: usize, + ) -> Option { + let mut guard = self.inner.write().await; + if let Some(entry) = guard.get_mut(session_id) { + entry.pending_messages = pending_messages; + entry.pending_interrupts = pending_interrupts; + return Some(entry.clone()); + } + None + } + + pub async fn list(&self) -> Vec { + let guard = self.inner.read().await; + let mut entries: Vec = guard.values().cloned().collect(); + entries.sort_by(|a, b| { + a.created_at_ms + .cmp(&b.created_at_ms) + .then_with(|| a.session_key.cmp(&b.session_key)) + }); + entries + } + + pub async fn remove(&self, session_id: &ConversationId) -> Option { + let mut guard = self.inner.write().await; + guard.remove(session_id) + } + + /// Insert a fully-formed metadata entry (used when adopting children into a new + /// parent session during a fork). This does not adjust timestamps or keys. + pub async fn register_imported(&self, metadata: SubagentMetadata) -> SubagentMetadata { + let mut guard = self.inner.write().await; + guard.insert(metadata.session_id, metadata.clone()); + metadata + } + + pub async fn prune(&self, mut predicate: F) -> Vec + where + F: FnMut(&SubagentMetadata) -> bool, + { + let mut guard = self.inner.write().await; + let ids: Vec = guard + .iter() + .filter_map(|(id, meta)| if predicate(meta) { Some(*id) } else { None }) + .collect(); + for id in &ids { + guard.remove(id); + } + ids + } + async fn insert_if_absent(&self, metadata: SubagentMetadata) -> SubagentMetadata { + let mut guard = self.inner.write().await; + if let Some(existing) = guard.get(&metadata.session_id) { + return existing.clone(); + } + let session_id = metadata.session_id; + guard.insert(session_id, metadata.clone()); + metadata + } +} + +fn unix_time_millis(time: SystemTime) -> i64 { + match time.duration_since(UNIX_EPOCH) { + Ok(duration) => duration.as_millis() as i64, + Err(err) => -(err.duration().as_millis() as i64), + } +} diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs index 9bda02c34e..8644468760 100644 --- a/codex-rs/core/src/tasks/mod.rs +++ b/codex-rs/core/src/tasks/mod.rs @@ -18,14 +18,19 @@ use tracing::warn; use crate::AuthManager; use crate::codex::Session; +use crate::codex::SessionSettingsUpdate; use crate::codex::TurnContext; +use crate::parse_turn_item; use crate::protocol::EventMsg; +use crate::protocol::ItemCompletedEvent; +use crate::protocol::ItemStartedEvent; use crate::protocol::TaskCompleteEvent; use crate::protocol::TurnAbortReason; use crate::protocol::TurnAbortedEvent; use crate::state::ActiveTurn; use crate::state::RunningTask; use crate::state::TaskKind; +use codex_protocol::models::ResponseItem; use codex_protocol::user_input::UserInput; pub(crate) use compact::CompactTask; @@ -150,6 +155,61 @@ impl Session { self.register_new_active_task(running_task).await; } + /// Start a new model turn driven by inbox-derived items (e.g., + /// synthetic `subagent_await` call/output pairs) without fabricating + /// additional user text. The model will see the updated history and + /// continue from there. + pub async fn autosubmit_inbox_task(self: &Arc, items: Vec) { + if items.is_empty() { + return; + } + + let turn_context = self.new_turn(SessionSettingsUpdate::default()).await; + + // Emit started/completed events for synthetic tool calls so UIs render them. + for item in &items { + if let Some(turn_item) = parse_turn_item(item) { + match item { + ResponseItem::FunctionCall { .. } => { + self.send_event( + turn_context.as_ref(), + EventMsg::ItemStarted(ItemStartedEvent { + thread_id: self.conversation_id(), + turn_id: turn_context.sub_id.clone(), + item: turn_item.clone(), + }), + ) + .await; + } + ResponseItem::FunctionCallOutput { .. } => { + self.send_event( + turn_context.as_ref(), + EventMsg::ItemCompleted(ItemCompletedEvent { + thread_id: self.conversation_id(), + turn_id: turn_context.sub_id.clone(), + item: turn_item.clone(), + }), + ) + .await; + } + _ => {} + } + } + } + + self.record_conversation_items(&turn_context, &items).await; + + // Kick off a RegularTask with no additional user input; `run_task` + // will treat this as an assistant-only turn based on existing + // history plus the inbox-derived items. + self.spawn_task( + Arc::clone(&turn_context), + Vec::new(), + crate::tasks::RegularTask, + ) + .await; + } + pub async fn abort_all_tasks(self: &Arc, reason: TurnAbortReason) { for task in self.take_all_running_tasks().await { self.handle_task_abort(task, reason.clone()).await; @@ -168,6 +228,7 @@ impl Session { *active = None; } drop(active); + let event = EventMsg::TaskComplete(TaskCompleteEvent { last_agent_message }); self.send_event(turn_context.as_ref(), event).await; } diff --git a/codex-rs/core/src/tasks/regular.rs b/codex-rs/core/src/tasks/regular.rs index 416dba3f7f..6f13fc2459 100644 --- a/codex-rs/core/src/tasks/regular.rs +++ b/codex-rs/core/src/tasks/regular.rs @@ -28,6 +28,6 @@ impl SessionTask for RegularTask { cancellation_token: CancellationToken, ) -> Option { let sess = session.clone_session(); - run_task(sess, ctx, input, cancellation_token).await + run_task(sess, ctx, input, true, cancellation_token).await } } diff --git a/codex-rs/core/src/tasks/user_shell.rs b/codex-rs/core/src/tasks/user_shell.rs index 32e8a25963..ba801fdfeb 100644 --- a/codex-rs/core/src/tasks/user_shell.rs +++ b/codex-rs/core/src/tasks/user_shell.rs @@ -86,6 +86,7 @@ impl SessionTask for UserShellCommandTask { cwd: cwd.clone(), parsed_cmd: parsed_cmd.clone(), source: ExecCommandSource::UserShell, + is_user_shell_command: true, interaction_input: None, }), ) diff --git a/codex-rs/core/src/tools/events.rs b/codex-rs/core/src/tools/events.rs index 37df12d4b0..94501feefc 100644 --- a/codex-rs/core/src/tools/events.rs +++ b/codex-rs/core/src/tools/events.rs @@ -76,6 +76,7 @@ pub(crate) async fn emit_exec_command_begin( cwd: cwd.to_path_buf(), parsed_cmd: parsed_cmd.to_vec(), source, + is_user_shell_command: matches!(source, ExecCommandSource::UserShell), interaction_input, }), ) diff --git a/codex-rs/core/src/tools/handlers/mod.rs b/codex-rs/core/src/tools/handlers/mod.rs index dcf848e376..aec76f4479 100644 --- a/codex-rs/core/src/tools/handlers/mod.rs +++ b/codex-rs/core/src/tools/handlers/mod.rs @@ -6,6 +6,7 @@ mod mcp_resource; mod plan; mod read_file; mod shell; +pub mod subagent; mod test_sync; mod unified_exec; mod view_image; @@ -21,6 +22,7 @@ pub use plan::PlanHandler; pub use read_file::ReadFileHandler; pub use shell::ShellCommandHandler; pub use shell::ShellHandler; +pub use subagent::SubagentToolHandler; pub use test_sync::TestSyncHandler; pub use unified_exec::UnifiedExecHandler; pub use view_image::ViewImageHandler; diff --git a/codex-rs/core/src/tools/handlers/subagent.rs b/codex-rs/core/src/tools/handlers/subagent.rs new file mode 100644 index 0000000000..8f55754ac5 --- /dev/null +++ b/codex-rs/core/src/tools/handlers/subagent.rs @@ -0,0 +1,2028 @@ +use std::borrow::Cow; +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Duration; +use std::time::Instant; + +use async_trait::async_trait; +use chrono::SecondsFormat; +use chrono::TimeZone; +use chrono::Utc; +use codex_protocol::AgentId; +use codex_protocol::ConversationId; +use codex_protocol::config_types::SandboxMode; +use codex_protocol::protocol::ExecCommandSource; +use serde::Deserialize; +use serde::Serialize; +use serde_json::json; + +use crate::codex::Session; +use crate::codex::TurnContext; +use crate::function_tool::FunctionCallError; +use crate::parse_command::parse_command; +use crate::subagents::ForkRequest; +use crate::subagents::LogEntry; +use crate::subagents::PruneRequest; +use crate::subagents::SendMessageRequest; +use crate::subagents::SpawnRequest; +use crate::subagents::SubagentCompletion; +use crate::subagents::SubagentManagerError; +use crate::subagents::SubagentMetadata; +use crate::subagents::SubagentOrigin; +use crate::subagents::SubagentStatus; +use crate::subagents::WatchdogAction; +use crate::tools::context::ToolInvocation; +use crate::tools::context::ToolOutput; +use crate::tools::context::ToolPayload; +use crate::tools::registry::ToolHandler; +use crate::tools::registry::ToolKind; +use codex_protocol::items::TurnItem; +use codex_protocol::models::ContentItem; +use codex_protocol::models::ReasoningItemReasoningSummary; +use codex_protocol::models::ResponseItem; +use codex_protocol::parse_command::ParsedCommand; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::ExecCommandBeginEvent; +use codex_protocol::protocol::ExecCommandEndEvent; +use codex_protocol::protocol::ItemCompletedEvent; +use codex_protocol::protocol::TaskCompleteEvent; +use codex_protocol::protocol::TokenCountEvent; + +const MAX_AWAIT_TIMEOUT_SECS: u64 = 30 * 60; +const MIN_WATCHDOG_INTERVAL_SECS: u64 = 30; +const DEFAULT_WATCHDOG_INTERVAL_SECS: u64 = 300; + +const ROOT_AGENT_ID: AgentId = 0; + +struct ExecEventLogger { + session: Arc, + turn: Arc, + call_id: String, + command: Vec, + cwd: PathBuf, + parsed_cmd: Vec, + start: Instant, +} + +impl ExecEventLogger { + async fn new( + session: Arc, + turn: Arc, + call_id: String, + command: Vec, + ) -> Self { + let parsed_cmd = parse_command(&command); + let cwd = turn.cwd.clone(); + session + .send_event( + &turn, + EventMsg::ExecCommandBegin(ExecCommandBeginEvent { + call_id: call_id.clone(), + turn_id: turn.sub_id.clone(), + command: command.clone(), + cwd: cwd.clone(), + parsed_cmd: parsed_cmd.clone(), + source: ExecCommandSource::Agent, + is_user_shell_command: false, + interaction_input: None, + }), + ) + .await; + + Self { + session, + turn, + call_id, + command, + cwd, + parsed_cmd, + start: Instant::now(), + } + } + + async fn success(&self, output: &str) { + self.finish(output, 0).await; + } + + async fn failure(&self, message: &str) { + self.finish(message, 1).await; + } + + async fn finish(&self, aggregated_output: &str, exit_code: i32) { + let duration = self.start.elapsed(); + let aggregated_output = clip_output(aggregated_output); + let stderr = if exit_code == 0 { + String::new() + } else { + aggregated_output.clone() + }; + + self.session + .send_event( + &self.turn, + EventMsg::ExecCommandEnd(ExecCommandEndEvent { + call_id: self.call_id.clone(), + turn_id: self.turn.sub_id.clone(), + command: self.command.clone(), + cwd: self.cwd.clone(), + parsed_cmd: self.parsed_cmd.clone(), + source: ExecCommandSource::Agent, + interaction_input: None, + stdout: String::new(), + stderr, + aggregated_output: aggregated_output.clone(), + exit_code, + duration, + formatted_output: aggregated_output, + }), + ) + .await; + } +} + +fn is_root_session( + caller_id: ConversationId, + registry: &HashMap, +) -> bool { + !registry + .values() + .any(|meta| meta.session_id == caller_id && meta.agent_id != ROOT_AGENT_ID) +} + +fn clip_output(out: &str) -> String { + let mut text = out.replace('\r', ""); + if text.len() > 4000 { + text.truncate(4000); + text.push('…'); + } + text +} + +#[derive(Serialize, Deserialize, Clone, Debug)] +#[serde(tag = "kind")] +enum SubagentRender { + Spawn { + label: String, + model: Option, + summary: Option, + }, + Fork { + label: String, + model: Option, + summary: Option, + }, + SendMessage { + label: String, + summary: Option, + }, + List { + count: usize, + }, + Await { + label: String, + timed_out: bool, + message: Option, + lifecycle_status: Option, + }, + Watchdog { + action: String, + interval_s: u64, + message: String, + }, + Cancel { + label: String, + }, + Prune { + counts: serde_json::Value, + }, + Logs { + rendered: String, + }, + Raw { + text: String, + }, +} + +fn summarize_tool_output(tool_name: &str, _arguments: &str, output: &ToolOutput) -> String { + let content = match output { + ToolOutput::Function { content, .. } => content, + ToolOutput::Mcp { result } => return format!("{result:?}"), + }; + let parsed: serde_json::Value = serde_json::from_str(content).unwrap_or_default(); + let render = match tool_name { + "subagent_spawn" | "subagent_fork" => { + let summary = parsed + .get("summary") + .and_then(|v| v.as_str()) + .map(str::to_string); + let model = parsed + .get("model") + .and_then(|v| v.as_str()) + .map(str::to_string); + let label = parsed + .get("label") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + if tool_name == "subagent_spawn" { + SubagentRender::Spawn { + label, + model, + summary, + } + } else { + SubagentRender::Fork { + label, + model, + summary, + } + } + } + "subagent_send_message" => { + let summary = parsed + .get("summary") + .and_then(|v| v.as_str()) + .map(str::to_string); + let label = parsed + .get("label") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + SubagentRender::SendMessage { label, summary } + } + "subagent_watchdog" => { + let action = parsed + .get("action") + .and_then(|v| v.as_str()) + .unwrap_or("started") + .to_string(); + let interval_s = parsed + .get("interval_s") + .and_then(serde_json::Value::as_u64) + .unwrap_or(DEFAULT_WATCHDOG_INTERVAL_SECS); + let msg = parsed + .get("message") + .and_then(|v| v.as_str()) + .unwrap_or( + "Watchdog ping — report current status, next step, and PLAN.md progress.", + ) + .to_string(); + SubagentRender::Watchdog { + action, + interval_s, + message: msg, + } + } + + "subagent_list" => { + let count = parsed + .get("sessions") + .and_then(|v| v.as_array()) + .map(Vec::len) + .unwrap_or(0); + SubagentRender::List { count } + } + "subagent_await" => { + let timed_out = parsed + .get("timed_out") + .and_then(serde_json::Value::as_bool) + .unwrap_or(false); + let label = parsed + .get("metadata") + .and_then(|m| m.get("label")) + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + let inbox_msg = parsed + .get("messages") + .and_then(|m| m.as_array()) + .and_then(|arr| arr.first()) + .and_then(|m| m.get("prompt")) + .and_then(|v| v.as_str()) + .map(std::string::ToString::to_string); + let completion_msg = parsed.get("completion").and_then(|c| { + if let Some(msg) = c + .get("Completed") + .and_then(|v| v.get("last_message")) + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + { + Some(format!("Completed: \"{msg}\"")) + } else if let Some(msg) = c + .get("Failed") + .and_then(|v| v.get("message")) + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + { + Some(format!("Failed: {msg}")) + } else if c.get("Canceled").is_some() { + Some("Canceled".to_string()) + } else if c.get("Completed").is_some() { + Some("Completed".to_string()) + } else { + None + } + }); + let merged_message = completion_msg.or(inbox_msg); + let lifecycle_status = parsed + .get("lifecycle_status") + .or_else(|| parsed.get("status")) + .and_then(|v| v.as_str()) + .map(str::to_string); + SubagentRender::Await { + label, + timed_out, + message: merged_message, + lifecycle_status, + } + } + "subagent_cancel" => { + let label = parsed + .get("label") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + SubagentRender::Cancel { label } + } + "subagent_prune" => { + let counts = parsed.get("counts").cloned().unwrap_or_default(); + SubagentRender::Prune { counts } + } + "subagent_logs" => { + let returned = parsed + .get("returned") + .and_then(serde_json::Value::as_u64) + .unwrap_or(0); + let events = parsed + .get("events") + .cloned() + .unwrap_or_else(|| serde_json::Value::Array(vec![])); + if let Ok(entries) = serde_json::from_value::>(events) { + let session_id = parsed + .get("session_id") + .and_then(|v| v.as_str()) + .and_then(|s| ConversationId::from_string(s).ok()) + .unwrap_or_default(); + let text = render_logs_as_text_with_max_lines( + session_id, + &entries, + parsed + .get("earliest_ms") + .and_then(serde_json::Value::as_i64), + parsed.get("latest_ms").and_then(serde_json::Value::as_i64), + returned as usize, + parsed + .get("total_available") + .and_then(serde_json::Value::as_u64) + .unwrap_or(0) as usize, + parsed + .get("more_available") + .and_then(serde_json::Value::as_bool) + .unwrap_or(false), + 30, + PageDirection::Backward, + ); + SubagentRender::Logs { rendered: text } + } else { + SubagentRender::Raw { + text: content.clone(), + } + } + } + _ => SubagentRender::Raw { + text: content.clone(), + }, + }; + + serde_json::to_string(&serde_json::json!({ "subagent_render": render })) + .unwrap_or_else(|_| content.clone()) +} + +#[derive(Serialize)] +struct ListEntry { + agent_id: AgentId, + parent_agent_id: Option, + session_id: ConversationId, + parent_session_id: Option, + origin: SubagentOrigin, + status: SubagentStatus, + label: Option, + summary: Option, + reasoning_header: Option, + started_at_ms: i64, + initial_message_count: usize, + pending_messages: usize, + pending_interrupts: usize, +} + +#[derive(Deserialize)] +struct SpawnArgsRaw { + prompt: String, + #[serde(default)] + label: Option, + #[serde(default)] + sandbox_mode: Option, + #[serde(default)] + model: Option, +} + +#[derive(Deserialize)] +struct ForkArgsRaw { + #[serde(default)] + prompt: Option, + #[serde(default)] + label: Option, + #[serde(default)] + sandbox_mode: Option, + #[serde(default)] + model: Option, +} + +fn parse_sandbox_mode(raw: Option) -> Result, FunctionCallError> { + let Some(raw) = raw else { + return Ok(None); + }; + + let norm = raw.trim().to_ascii_lowercase().replace(['_', ' '], "-"); + let collapsed: Cow<'_, str> = Cow::Owned(norm.replace('-', "")); + + let mode = match norm.as_str() { + "read-only" | "read" | "readonly" => Some(SandboxMode::ReadOnly), + "workspace-write" | "workspacewrite" | "workspace" => Some(SandboxMode::WorkspaceWrite), + "danger-full-access" | "dangerfullaccess" | "danger" | "fullaccess" => { + Some(SandboxMode::DangerFullAccess) + } + _ => match collapsed.as_ref() { + "readonly" => Some(SandboxMode::ReadOnly), + "workspacewrite" => Some(SandboxMode::WorkspaceWrite), + "dangerfullaccess" | "danger" | "fullaccess" => Some(SandboxMode::DangerFullAccess), + _ => None, + }, + }; + + mode.map(Some).ok_or_else(|| { + FunctionCallError::RespondToModel(format!( + "unknown sandbox_mode '{raw}'; expected one of read-only, workspace-write, danger-full-access" + )) + }) +} + +#[derive(Deserialize)] +struct SendMessageArgs { + #[serde(default)] + prompt: Option, + #[serde(default)] + label: Option, + agent_id: AgentId, + #[serde(default)] + interrupt: bool, +} + +#[derive(Deserialize)] +struct WatchdogArgs { + agent_id: AgentId, + #[serde(default)] + interval_s: Option, + #[serde(default)] + message: Option, + #[serde(default)] + cancel: Option, +} + +#[derive(Deserialize)] +struct AwaitArgs { + #[serde(default)] + timeout_s: Option, +} + +#[derive(Deserialize)] +struct CancelArgs { + agent_id: AgentId, +} + +#[derive(Deserialize)] +#[serde(untagged)] +enum PruneArgs { + ByIds { + agent_ids: Vec, + #[serde(default)] + completed_only: Option, + }, + All { + all: bool, + #[serde(default)] + completed_only: Option, + }, +} + +pub struct SubagentToolHandler; + +#[async_trait] +impl ToolHandler for SubagentToolHandler { + fn kind(&self) -> ToolKind { + ToolKind::Function + } + + async fn handle(&self, invocation: ToolInvocation) -> Result { + let ToolInvocation { + session, + turn, + call_id, + tool_name, + payload, + .. + } = invocation; + + let arguments = match payload { + ToolPayload::Function { arguments } => arguments, + _ => { + return Err(FunctionCallError::RespondToModel( + "subagent tools require function arguments".to_string(), + )); + } + }; + + let registry = session.services.subagents.clone(); + let manager = session.services.subagent_manager.clone(); + let caller_id = session.conversation_id(); + let registry_entries = registry.list().await; + let registry_by_agent: HashMap = registry_entries + .iter() + .map(|entry| (entry.agent_id, entry.clone())) + .collect(); + let is_root_agent = is_root_session(caller_id, ®istry_by_agent); + let mut exec_logger: Option = None; + + let result: Result = async { + match tool_name.as_str() { + "subagent_spawn" => { + let args: SpawnArgsRaw = serde_json::from_str(&arguments).map_err(|err| { + FunctionCallError::RespondToModel(format!( + "failed to parse subagent_spawn arguments: {err}" + )) + })?; + let SpawnArgsRaw { + prompt, + label: raw_label, + sandbox_mode, + model, + } = args; + let sandbox_mode = parse_sandbox_mode(sandbox_mode)?; + let model_clone = model.clone(); + let label = normalize_label(raw_label); + let summary = summarize_prompt(&prompt); + if is_root_agent { + let display_label = + label.clone().unwrap_or_else(|| "".to_string()); + exec_logger = Some( + ExecEventLogger::new( + session.clone(), + turn.clone(), + call_id.clone(), + vec![format!("Spawned subagent {display_label}")], + ) + .await, + ); + } + let metadata = manager + .spawn( + session.clone(), + turn.clone(), + SpawnRequest { + prompt, + label, + summary, + sandbox_mode, + model, + }, + ) + .await + .map_err(|err| map_manager_error(err, None))?; + let response = json!({ + "session_id": metadata.session_id, + "agent_id": metadata.agent_id, + "parent_agent_id": metadata.parent_agent_id, + "origin": metadata.origin, + "status": metadata.status, + "model": model_clone, + "label": metadata.label, + "summary": metadata.summary, + "parent_session_id": metadata.parent_session_id, + "started_at_ms": metadata.created_at_ms, + "initial_message_count": metadata.initial_message_count, + "pending_messages": metadata.pending_messages, + "pending_interrupts": metadata.pending_interrupts, + }); + Ok(ToolOutput::Function { + content: response.to_string(), + content_items: None, + success: Some(true), + }) + } + "subagent_fork" => { + let args: ForkArgsRaw = serde_json::from_str(&arguments).map_err(|err| { + FunctionCallError::RespondToModel(format!( + "failed to parse subagent_fork arguments: {err}" + )) + })?; + let ForkArgsRaw { + prompt, + label: raw_label, + sandbox_mode, + model, + } = args; + let sandbox_mode = parse_sandbox_mode(sandbox_mode)?; + let model_clone = model.clone(); + let prompt_clone = prompt.clone(); + let parent_session_id = caller_id; + let label = normalize_label(raw_label); + let summary = summarize_optional_prompt(&prompt); + let initial_message_count = session.history_len().await; + if is_root_agent { + let display_label = + label.clone().unwrap_or_else(|| "".to_string()); + exec_logger = Some( + ExecEventLogger::new( + session.clone(), + turn.clone(), + call_id.clone(), + vec![format!("Forked subagent {display_label}")], + ) + .await, + ); + } + + let metadata = manager + .fork( + session.clone(), + turn.clone(), + ForkRequest { + parent_session_id, + initial_message_count, + label, + summary, + call_id: call_id.clone(), + arguments: arguments.clone(), + prompt, + sandbox_mode, + model, + }, + ) + .await + .map_err(|err| map_manager_error(err, None))?; + + let child_id = metadata.session_id; + let parent_payload = json!({ + "role": "parent", + "child_session_id": child_id, + "parent_session_id": parent_session_id, + "label": metadata.label, + "summary": metadata.summary, + "prompt": prompt_clone, + }); + + let response = json!({ + "session_id": metadata.session_id, + "agent_id": metadata.agent_id, + "parent_agent_id": metadata.parent_agent_id, + "origin": metadata.origin, + "status": metadata.status, + "model": model_clone, + "label": metadata.label, + "summary": metadata.summary, + "parent_session_id": metadata.parent_session_id, + "started_at_ms": metadata.created_at_ms, + "initial_message_count": metadata.initial_message_count, + "pending_messages": metadata.pending_messages, + "pending_interrupts": metadata.pending_interrupts, + "payload": parent_payload, + }); + Ok(ToolOutput::Function { + content: response.to_string(), + content_items: None, + success: Some(true), + }) + } + "subagent_send_message" => { + let args: SendMessageArgs = + serde_json::from_str(&arguments).map_err(|err| { + FunctionCallError::RespondToModel(format!( + "failed to parse subagent_send_message arguments: {err}" + )) + })?; + let SendMessageArgs { + prompt, + label: raw_label, + agent_id, + interrupt, + } = args; + if agent_id == 0 && interrupt { + return Err(FunctionCallError::RespondToModel( + "cannot send an interrupt to agent 0 (the root UI thread)".to_string(), + )); + } + + let label = normalize_label(raw_label); + let summary = summarize_optional_prompt(&prompt); + + let sender_metadata = registry_by_agent + .values() + .find(|meta| meta.session_id == caller_id) + .cloned(); + let sender_agent_id = sender_metadata + .as_ref() + .map(|meta| meta.agent_id) + .unwrap_or(ROOT_AGENT_ID); + + if agent_id == 0 { + // Root-directed message from a subagent. Treat this as a + // lightweight inbox entry for the root session so UIs can + // autosubmit follow-ups when idle. + if sender_agent_id == ROOT_AGENT_ID { + return Err(FunctionCallError::RespondToModel( + "root agent cannot target agent 0; send a normal user message instead" + .to_string(), + )); + } + + let sender_metadata = match sender_metadata { + Some(meta) => meta, + None => { + return Err(FunctionCallError::RespondToModel( + "cannot send a message to agent 0 from an unknown subagent" + .to_string(), + )); + } + }; + + // Walk up the parent_session_id chain to find the root session id. + let mut root_session_id = caller_id; + loop { + if let Some(meta) = registry_entries + .iter() + .find(|m| m.session_id == root_session_id) + && let Some(parent) = meta.parent_session_id { + root_session_id = parent; + continue; + } + break; + } + + let display_label = label + .clone() + .unwrap_or_else(|| "".to_string()); + if is_root_agent { + exec_logger = Some( + ExecEventLogger::new( + session.clone(), + turn.clone(), + call_id.clone(), + vec![format!("Sent message to root from subagent {display_label}")], + ) + .await, + ); + } + + manager.send_message_to_root( + root_session_id, + caller_id, + prompt, + sender_metadata, + ) + .await + .map_err(|err| map_manager_error(err, Some(agent_id)))?; + + let response = json!({ + "session_id": root_session_id, + "agent_id": agent_id, + "label": label, + "summary": summary, + }); + Ok(ToolOutput::Function { + content: response.to_string(), + content_items: None, + success: Some(true), + }) + } else { + let session_id = require_agent_session(®istry_by_agent, agent_id)?; + let display_label = label + .clone() + .or_else(|| { + registry_by_agent + .get(&agent_id) + .and_then(|m| m.label.clone()) + }) + .unwrap_or_else(|| "".to_string()); + + if is_root_agent { + exec_logger = Some( + ExecEventLogger::new( + session.clone(), + turn.clone(), + call_id.clone(), + vec![format!("Sent message to subagent {display_label}")], + ) + .await, + ); + } + + let metadata = manager + .send_message(SendMessageRequest { + session_id, + label, + summary, + prompt, + agent_id, + sender_agent_id, + interrupt, + }) + .await + .map_err(|err| map_manager_error(err, Some(agent_id)))?; + + let response = json!({ + "session_id": metadata.session_id, + "agent_id": metadata.agent_id, + "parent_agent_id": metadata.parent_agent_id, + "origin": metadata.origin, + "status": metadata.status, + "label": metadata.label, + "summary": metadata.summary, + "parent_session_id": metadata.parent_session_id, + "started_at_ms": metadata.created_at_ms, + "initial_message_count": metadata.initial_message_count, + "pending_messages": metadata.pending_messages, + "pending_interrupts": metadata.pending_interrupts, + }); + Ok(ToolOutput::Function { + content: response.to_string(), + content_items: None, + success: Some(true), + }) + } + } + "subagent_watchdog" => { + let args: WatchdogArgs = serde_json::from_str(&arguments).map_err(|err| { + FunctionCallError::RespondToModel(format!( + "failed to parse subagent_watchdog arguments: {err}" + )) + })?; + + let interval_raw = args.interval_s.unwrap_or(DEFAULT_WATCHDOG_INTERVAL_SECS); + if interval_raw < MIN_WATCHDOG_INTERVAL_SECS { + return Err(FunctionCallError::RespondToModel(format!( + "interval_s must be at least {MIN_WATCHDOG_INTERVAL_SECS} seconds" + ))); + } + let message = args + .message + .clone() + .filter(|m| !m.trim().is_empty()) + .unwrap_or_else(|| { + "Watchdog ping — report current status, next step, and PLAN.md progress.".to_string() + }); + let cancel = args.cancel.unwrap_or(false); + + let caller_agent_id = if is_root_agent { + ROOT_AGENT_ID + } else { + registry_by_agent + .iter() + .find(|(_, meta)| meta.session_id == caller_id) + .map(|(id, _)| *id) + .unwrap_or(ROOT_AGENT_ID) + }; + + let action = manager + .watchdog_action( + session.conversation_id(), + caller_agent_id, + args.agent_id, + interval_raw, + message.clone(), + cancel, + ) + .await + .map_err(|err| map_manager_error(err, Some(args.agent_id)))?; + + if is_root_agent { + let verb = match action { + WatchdogAction::Started => "Started", + WatchdogAction::Replaced => "Replaced", + WatchdogAction::Canceled => "Canceled", + WatchdogAction::NotFound => "No watchdog", + }; + exec_logger = Some( + ExecEventLogger::new( + session.clone(), + turn.clone(), + call_id.clone(), + vec![format!("{verb} watchdog for agent {}", args.agent_id)], + ) + .await, + ); + } + + let response = json!({ + "agent_id": args.agent_id, + "interval_s": interval_raw, + "message": message, + "action": action, + }); + + Ok(ToolOutput::Function { + content: response.to_string(), + content_items: None, + success: Some(action != WatchdogAction::NotFound), + }) + }, + + "subagent_list" => { + let entries = registry_entries + .iter() + .filter(|m| m.parent_session_id == Some(caller_id)) + .map(|entry| ListEntry { + agent_id: entry.agent_id, + parent_agent_id: Some(entry.parent_agent_id.unwrap_or(ROOT_AGENT_ID)), + session_id: entry.session_id, + parent_session_id: entry.parent_session_id, + origin: entry.origin, + status: entry.status, + label: entry.label.clone(), + summary: entry.summary.clone(), + reasoning_header: entry.reasoning_header.clone(), + started_at_ms: entry.created_at_ms, + initial_message_count: entry.initial_message_count, + pending_messages: entry.pending_messages, + pending_interrupts: entry.pending_interrupts, + }) + .collect::>(); + let payload = json!({ + "sessions": entries + }); + if is_root_agent { + exec_logger = Some( + ExecEventLogger::new( + session.clone(), + turn.clone(), + call_id.clone(), + vec!["Listed subagents".to_string()], + ) + .await, + ); + } + Ok(ToolOutput::Function { + content: payload.to_string(), + content_items: None, + success: Some(true), + }) + } + "subagent_await" => { + let args: AwaitArgs = serde_json::from_str(&arguments).map_err(|err| { + FunctionCallError::RespondToModel(format!( + "failed to parse subagent_await arguments: {err}" + )) + })?; + let timeout = resolve_await_timeout( + args.timeout_s, + )?; + + let target_session = registry_entries + .iter() + .filter(|m| m.parent_session_id == Some(caller_id)) + .max_by_key(|m| m.pending_messages) + .map(|m| m.session_id); + + let Some(session_id) = target_session else { + return Err(FunctionCallError::RespondToModel( + "no active subagents to await; start one with subagent_spawn first" + .to_string(), + )); + }; + + if is_root_agent { + let display_label = registry_entries + .iter() + .find(|m| m.session_id == session_id) + .and_then(|m| m.label.clone()) + .unwrap_or_else(|| "subagent".to_string()); + exec_logger = Some( + ExecEventLogger::new( + session.clone(), + turn.clone(), + call_id.clone(), + vec![format!("Awaited subagent {display_label}")], + ) + .await, + ); + } + + match manager + .await_inbox_and_completion(&session_id, Some(timeout)) + .await + { + Ok(result) => { + let completion_status = + result.completion.as_ref().map(completion_status); + let lifecycle_status = result.metadata.status; + let started_at_ms = result.metadata.created_at_ms; + let response = json!({ + "session_id": result.metadata.session_id, + "completion_status": completion_status, + "lifecycle_status": lifecycle_status, + "started_at_ms": started_at_ms, + "timed_out": false, + "messages": result.messages, + "completion": result.completion, + "metadata": result.metadata, + "injected": false, + }); + Ok(ToolOutput::Function { + content: response.to_string(), + content_items: None, + success: Some(true), + }) + } + Err(SubagentManagerError::AwaitTimedOut { + session_id: sid, + agent_id: _timed_agent, + timeout_ms: _waited_ms, + }) => { + let metadata = manager.metadata(&sid).await; + let lifecycle_status = metadata.as_ref().map(|meta| meta.status); + let started_at_ms = metadata.as_ref().map(|meta| meta.created_at_ms); + let response = json!({ + "session_id": sid, + "completion_status": None::, + "lifecycle_status": lifecycle_status, + "started_at_ms": started_at_ms, + "timed_out": true, + "messages": Vec::::new(), + "completion": None::, + "metadata": metadata, + "injected": false, + }); + Ok(ToolOutput::Function { + content: response.to_string(), + content_items: None, + success: Some(false), + }) + } + Err(err) => Err(map_manager_error(err, None)), + } + } + "subagent_prune" => { + let args: PruneArgs = serde_json::from_str(&arguments).map_err(|err| { + FunctionCallError::RespondToModel(format!( + "failed to parse subagent_prune arguments: {err}" + )) + })?; + let request = match args { + PruneArgs::ByIds { + agent_ids, + completed_only, + } => { + let session_ids = agent_ids + .into_iter() + .filter_map(|id| registry_by_agent.get(&id).map(|m| m.session_id)) + .collect::>(); + PruneRequest { + session_ids: Some(session_ids), + all: false, + completed_only: completed_only.unwrap_or(true), + } + } + PruneArgs::All { + all, + completed_only, + } => PruneRequest { + session_ids: None, + all, + completed_only: completed_only.unwrap_or(true), + }, + }; + if is_root_agent { + exec_logger = Some( + ExecEventLogger::new( + session.clone(), + turn.clone(), + call_id.clone(), + vec!["Pruned subagents".to_string()], + ) + .await, + ); + } + let request_echo = + serde_json::from_str::(&arguments).unwrap_or_default(); + let report = manager + .prune(request) + .await + .map_err(|err| map_manager_error(err, None))?; + + let response = json!({ + "request": request_echo, + "pruned": report.pruned, + "skipped_active": report.skipped_active, + "unknown": report.unknown, + "errors": report.errors, + "counts": { + "pruned": report.pruned.len(), + "skipped_active": report.skipped_active.len(), + "unknown": report.unknown.len(), + "errors": report.errors.len(), + } + }); + Ok(ToolOutput::Function { + content: response.to_string(), + content_items: None, + success: Some(report.errors.is_empty()), + }) + } + "subagent_logs" => { + let args: LogsArgs = serde_json::from_str(&arguments).map_err(|err| { + FunctionCallError::RespondToModel(format!( + "failed to parse subagent_logs arguments: {err}" + )) + })?; + let LogsArgs { + agent_id, + limit, + max_bytes, + since_ms, + before_ms, + } = args; + let session_id = require_agent_session(®istry_by_agent, agent_id)?; + + if is_root_agent { + let display_label = registry_by_agent + .get(&agent_id) + .and_then(|m| m.label.clone()) + .unwrap_or_else(|| "".to_string()); + exec_logger = Some( + ExecEventLogger::new( + session.clone(), + turn.clone(), + call_id.clone(), + vec![format!("Fetched subagent logs {display_label}")], + ) + .await, + ); + } + + let snapshot = manager + .snapshot_logs(&session_id) + .await + .map_err(|err| map_manager_error(err, Some(agent_id)))?; + + let response = render_logs_payload( + session_id, snapshot, limit, max_bytes, since_ms, before_ms, + ); + + Ok(ToolOutput::Function { + content: response.to_string(), + content_items: None, + success: Some(true), + }) + } + "subagent_cancel" => { + let args: CancelArgs = serde_json::from_str(&arguments).map_err(|err| { + FunctionCallError::RespondToModel(format!( + "failed to parse subagent_cancel arguments: {err}" + )) + })?; + let CancelArgs { agent_id } = args; + let session_id = require_agent_session(®istry_by_agent, agent_id)?; + + if is_root_agent { + let display_label = registry_by_agent + .get(&agent_id) + .and_then(|m| m.label.clone()) + .unwrap_or_else(|| "".to_string()); + exec_logger = Some( + ExecEventLogger::new( + session.clone(), + turn.clone(), + call_id.clone(), + vec![format!("Canceled subagent {display_label}")], + ) + .await, + ); + } + + let metadata = manager + .cancel(session_id) + .await + .map_err(|err| map_manager_error(err, Some(agent_id)))?; + + let response = json!({ + "session_id": metadata.session_id, + "origin": metadata.origin, + "status": metadata.status, + "label": metadata.label, + "summary": metadata.summary, + "parent_session_id": metadata.parent_session_id, + "started_at_ms": metadata.created_at_ms, + "initial_message_count": metadata.initial_message_count, + }); + + Ok(ToolOutput::Function { + content: response.to_string(), + content_items: None, + success: Some(true), + }) + } + _ => Err(FunctionCallError::RespondToModel( + "unknown subagent tool".to_string(), + )), + } + } + .await; + if let Some(logger) = &exec_logger { + match &result { + Ok(out) => { + let summary = summarize_tool_output(&tool_name, &arguments, out); + logger.success(&summary).await; + } + Err(err) => logger.failure(&err.to_string()).await, + } + } + + result + } +} + +/// Build the JSON payload returned by `subagent_logs` for a given log snapshot. +pub fn render_logs_payload( + session_id: ConversationId, + logs: Vec, + limit: Option, + max_bytes: Option, + since_ms: Option, + before_ms: Option, +) -> serde_json::Value { + // Default limit of 5 if not specified or invalid (0). + let count = limit.unwrap_or(5).max(1); + + // Filter by since_ms / before_ms if provided. + let filtered = logs + .into_iter() + .filter(|e| { + let ts = e.timestamp_ms; + let since_ok = since_ms.map(|s| ts > s).unwrap_or(true); + let before_ok = before_ms.map(|b| ts < b).unwrap_or(true); + since_ok && before_ok + }) + .collect::>(); + + let total_available = filtered.len(); + let (window, truncated_by_bytes) = apply_log_window(filtered, count, max_bytes); + + let returned = window.len(); + let more_available = returned < total_available || truncated_by_bytes; + let earliest_ms = window.first().map(|e| e.timestamp_ms); + let latest_ms = window.last().map(|e| e.timestamp_ms); + + json!({ + "session_id": session_id, + "returned": returned, + "total_available": total_available, + "more_available": more_available, + "earliest_ms": earliest_ms, + "latest_ms": latest_ms, + "events": window, + }) +} + +fn format_timestamp(ts_ms: i64) -> String { + if ts_ms <= 0 { + return "0000-00-00T00:00:00.000Z".to_string(); + } + + // Convert ms since Unix epoch to an RFC3339 timestamp with millisecond + // precision. Clamp invalid inputs to a stable placeholder instead of + // panicking. + let secs = ts_ms.div_euclid(1_000); + let millis = ts_ms.rem_euclid(1_000).unsigned_abs() as u32; + let nanos = millis * 1_000_000; + + match Utc.timestamp_opt(secs, nanos).single() { + Some(dt) => dt.to_rfc3339_opts(SecondsFormat::Millis, true), + None => "0000-00-00T00:00:00.000Z".to_string(), + } +} + +/// High-level activity state derived from a log window. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SubagentActivity { + /// The model is actively producing reasoning or message deltas. + Working, + /// Waiting on a tool call (exec, web, etc.) to complete. + WaitingOnTool, + /// No obvious in-flight work in this window. + Idle, +} + +pub fn classify_activity(logs: &[LogEntry]) -> SubagentActivity { + let mut saw_exec_begin = false; + let mut saw_exec_end = false; + let mut saw_streaming = false; + + for entry in logs { + match &entry.event.msg { + EventMsg::ExecCommandBegin(_) => { + saw_exec_begin = true; + } + EventMsg::ExecCommandEnd(ExecCommandEndEvent { .. }) => { + saw_exec_end = true; + } + EventMsg::AgentMessageContentDelta(_) | EventMsg::ReasoningContentDelta(_) => { + saw_streaming = true; + } + _ => {} + } + } + + if saw_exec_begin && !saw_exec_end { + SubagentActivity::WaitingOnTool + } else if saw_streaming { + SubagentActivity::Working + } else { + SubagentActivity::Idle + } +} + +/// Direction for paged rendering of log lines. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PageDirection { + /// Render the most recent lines, suitable for a "tail" view. + Backward, + /// Render the earliest lines in the window, suitable for forward paging + /// given a `since_ms` cursor. + Forward, +} + +/// A page of rendered log output plus cursors for navigation. +#[derive(Debug, Clone)] +pub struct RenderedPage { + pub lines: Vec, + pub status: SubagentActivity, + pub first_timestamp_ms: Option, + pub last_timestamp_ms: Option, + pub has_more_before: bool, + pub has_more_after: bool, +} + +fn render_logs_lines( + session_id: ConversationId, + logs: &[LogEntry], + _earliest_ms: Option, + latest_ms: Option, + _returned: usize, + _total_available: usize, + _more_available: bool, +) -> (SubagentActivity, Vec) { + let latest_ms = latest_ms + .or_else(|| logs.iter().map(|e| e.timestamp_ms).max()) + .unwrap_or(0); + + let mut lines = Vec::new(); + let activity = classify_activity(logs); + let activity_str = match activity { + SubagentActivity::Working => "working", + SubagentActivity::WaitingOnTool => "waiting_on_tool", + SubagentActivity::Idle => "idle", + }; + // Header focuses on high-level state; paging hints are added later in + // `render_logs_page` once we know whether there is older/newer history + // in the current window. + lines.push(format!("Session {session_id} • status={activity_str}")); + + // Accumulators for the simple shapes we care about today. + let mut last_assistant_message: Option<(i64, String)> = None; + let mut reasoning_summary: Option<(i64, String)> = None; + let mut task_complete_ts: Option = None; + + // Exec-specific / streaming accumulators. + let mut reasoning_delta: Option<(i64, usize, String)> = None; + let mut message_delta: Option<(i64, usize, String)> = None; + let mut exec_begin: Option<(i64, ExecCommandBeginEvent)> = None; + + for entry in logs { + let ts = entry.timestamp_ms; + match &entry.event.msg { + EventMsg::AgentMessage(ev) => { + last_assistant_message = Some((ts, ev.message.clone())); + } + EventMsg::RawResponseItem(ev) => match &ev.item { + ResponseItem::Reasoning { summary, .. } => { + if let Some(ReasoningItemReasoningSummary::SummaryText { text }) = + summary.first() + { + reasoning_summary = Some((ts, text.clone())); + } + } + ResponseItem::Message { content, .. } => { + if let Some(first) = content.first() + && let ContentItem::OutputText { text } = first + { + last_assistant_message = Some((ts, text.clone())); + } + } + _ => {} + }, + EventMsg::TokenCount(TokenCountEvent { .. }) => { + // Deliberately ignored in the human transcript; callers that + // care about usage can inspect the raw JSON events instead. + } + EventMsg::TaskComplete(TaskCompleteEvent { .. }) => { + task_complete_ts = Some(ts); + } + EventMsg::ReasoningContentDelta(ev) => { + let entry = reasoning_delta.get_or_insert((ts, 0usize, String::new())); + // Timestamp reflects the most recent contributing delta so the + // rendered line is an "as of" marker, not just the start. + entry.0 = ts; + entry.1 = entry.1.saturating_add(1); + entry.2.push_str(&ev.delta); + } + EventMsg::AgentMessageContentDelta(ev) => { + let entry = message_delta.get_or_insert((ts, 0usize, String::new())); + entry.0 = ts; + entry.1 = entry.1.saturating_add(1); + entry.2.push_str(&ev.delta); + } + EventMsg::ExecCommandBegin(ev) => { + exec_begin = Some((ts, ev.clone())); + } + EventMsg::ItemCompleted(ItemCompletedEvent { item, .. }) => { + if let TurnItem::Reasoning(reasoning) = item + && let Some(first) = reasoning.summary_text.first() + { + reasoning_summary = Some((ts, first.clone())); + } + } + _ => {} + } + } + + let has_exec = exec_begin.is_some(); + + if has_exec { + if let Some((ts, count, full_text)) = reasoning_delta { + let ts_str = format_timestamp(ts); + let label = if count == 1 { "delta" } else { "deltas" }; + lines.push(format!("{ts_str} Thinking: {full_text} ({count} {label})")); + } + + if let Some((ts, summary)) = reasoning_summary { + let ts_str = format_timestamp(ts); + lines.push(format!("{ts_str} Reasoning summary: {summary}")); + } + + if let Some((ts, begin)) = exec_begin { + let ts_str = format_timestamp(ts); + let dur_ms = (latest_ms - ts).max(0); + let dur_secs = dur_ms as f64 / 1000.0; + lines.push(format!( + "{ts_str} 🛠 exec {} · cwd={} · running ({dur_secs:.1}s)", + begin.command.join(" "), + begin.cwd.display(), + )); + } + } else { + if let Some((ts, count, full_text)) = reasoning_delta { + let ts_str = format_timestamp(ts); + let label = if count == 1 { "delta" } else { "deltas" }; + lines.push(format!("{ts_str} Thinking: {full_text} ({count} {label})")); + } + + if let Some((ts, count, full_text)) = message_delta { + let ts_str = format_timestamp(ts); + if count <= 1 { + lines.push(format!( + "{ts_str} Assistant (typing): {full_text} (1 chunk)" + )); + } else { + lines.push(format!( + "{ts_str} Assistant (typing): {full_text} ({count} chunks)" + )); + } + } + + if let Some((ts, msg)) = last_assistant_message { + let ts_str = format_timestamp(ts); + lines.push(format!("{ts_str} Assistant: {msg}")); + } + + if let Some((ts, summary)) = reasoning_summary { + let ts_str = format_timestamp(ts); + lines.push(format!("{ts_str} Thinking: {summary}")); + } + + if let Some(ts) = task_complete_ts { + let ts_str = format_timestamp(ts); + lines.push(format!("{ts_str} Task complete")); + } + } + + (activity, lines) +} + +/// Render a single paged view over a log window, returning both the rendered +/// lines and cursor information for paging. +#[allow(clippy::too_many_arguments)] +pub fn render_logs_page( + session_id: ConversationId, + logs: &[LogEntry], + earliest_ms: Option, + latest_ms: Option, + returned: usize, + total_available: usize, + more_available: bool, + max_lines: usize, + direction: PageDirection, +) -> RenderedPage { + let max_lines = max_lines.max(1); + let (status, full_lines) = render_logs_lines( + session_id, + logs, + earliest_ms, + latest_ms, + returned, + total_available, + more_available, + ); + + if full_lines.is_empty() { + return RenderedPage { + lines: Vec::new(), + status, + first_timestamp_ms: earliest_ms, + last_timestamp_ms: latest_ms, + has_more_before: false, + has_more_after: false, + }; + } + + // Preserve the header, page the body. + let mut iter = full_lines.into_iter(); + let mut header = iter.next().unwrap_or_default(); + let body: Vec = iter.collect(); + let body_len = body.len(); + + let trimmed_body: Vec = if body_len <= max_lines { + body + } else { + match direction { + PageDirection::Backward => body[body_len - max_lines..].to_vec(), + PageDirection::Forward => body[..max_lines].to_vec(), + } + }; + + let mut lines = Vec::with_capacity(1 + trimmed_body.len()); + lines.push(header.clone()); + lines.extend(trimmed_body); + + let first_timestamp_ms = earliest_ms.or_else(|| logs.first().map(|e| e.timestamp_ms)); + let last_timestamp_ms = latest_ms.or_else(|| logs.last().map(|e| e.timestamp_ms)); + + let has_more_before = + matches!(direction, PageDirection::Backward) && total_available > returned; + let has_more_after = matches!(direction, PageDirection::Forward) && more_available; + + // Extend the header with explicit paging hints so callers can tell + // whether there is older history or whether this page is at the + // latest known point in time, without reasoning about event + // counts. We deliberately avoid talking about "newer logs" to + // prevent confusion while the subagent is still working. + let older = if has_more_before { "true" } else { "false" }; + let at_latest = if has_more_after { "false" } else { "true" }; + header.push_str(&format!(" • older_logs={older} • at_latest={at_latest}")); + + if let Some(first) = lines.first_mut() { + *first = header; + } + + RenderedPage { + lines, + status, + first_timestamp_ms, + last_timestamp_ms, + has_more_before, + has_more_after, + } +} + +/// Render a human-friendly transcript for a subagent_logs payload. +/// +/// This is intentionally conservative and focuses on the common shapes we +/// currently exercise in tests: simple assistant replies, reasoning summaries, +/// token counts, and exec_command_begin events. +pub fn render_logs_as_text( + session_id: ConversationId, + logs: &[LogEntry], + earliest_ms: Option, + latest_ms: Option, + returned: usize, + total_available: usize, + more_available: bool, +) -> String { + let page = render_logs_page( + session_id, + logs, + earliest_ms, + latest_ms, + returned, + total_available, + more_available, + usize::MAX, + PageDirection::Backward, + ); + + page.lines.join("\n") +} + +/// Variant of `render_logs_as_text` that applies a `max_lines` budget and a +/// paging direction. This is intended for UIs that want a bounded transcript +/// (for example, the last 30 lines) while still reusing the same aggregation +/// logic as the full-text renderer. +#[allow(clippy::too_many_arguments)] +pub fn render_logs_as_text_with_max_lines( + session_id: ConversationId, + logs: &[LogEntry], + earliest_ms: Option, + latest_ms: Option, + returned: usize, + total_available: usize, + more_available: bool, + max_lines: usize, + direction: PageDirection, +) -> String { + let page = render_logs_page( + session_id, + logs, + earliest_ms, + latest_ms, + returned, + total_available, + more_available, + max_lines, + direction, + ); + + page.lines.join("\n") +} + +fn map_manager_error( + err: SubagentManagerError, + agent_id_hint: Option, +) -> FunctionCallError { + match err { + SubagentManagerError::NotFound => { + if let Some(agent_id) = agent_id_hint { + FunctionCallError::RespondToModel(format!( + "agent_id {agent_id} is no longer active; refresh subagent_list" + )) + } else { + FunctionCallError::RespondToModel("unknown session id".to_string()) + } + } + SubagentManagerError::LaunchFailed(message) => { + FunctionCallError::RespondToModel(format!("subagent launch failed: {message}")) + } + SubagentManagerError::LimitReached { limit } => FunctionCallError::RespondToModel(format!( + "subagent limit reached: at most {limit} active subagents per session" + )), + SubagentManagerError::AwaitTimedOut { + session_id, + agent_id, + timeout_ms, + } => FunctionCallError::RespondToModel(format!( + "timed out after {timeout_ms} ms waiting for agent_id {agent_id} (session {session_id})" + )), + SubagentManagerError::InvalidPruneRequest(message) => { + FunctionCallError::RespondToModel(message) + } + SubagentManagerError::SandboxOverrideForbidden { requested, parent } => { + FunctionCallError::RespondToModel(format!( + "sandbox_mode {requested:?} not permitted; parent session runs in {parent:?}" + )) + } + SubagentManagerError::AgentIdMismatch { + session_id, + agent_id, + } => FunctionCallError::RespondToModel(format!( + "agent_id {agent_id} mismatch for session {session_id}: refresh subagent_list before sending" + )), + } +} + +fn normalize_label(label: Option) -> Option { + label + .map(|s| collapse_whitespace(s.trim())) + .filter(|s| !s.is_empty()) +} + +fn summarize_prompt(prompt: &str) -> Option { + let collapsed = collapse_whitespace(prompt.trim()); + if collapsed.is_empty() { + return None; + } + let mut summary = collapsed.chars().take(80).collect::(); + if collapsed.chars().count() > summary.chars().count() { + summary.push('…'); + } + Some(summary) +} + +fn summarize_optional_prompt(prompt: &Option) -> Option { + prompt.as_deref().and_then(summarize_prompt) +} + +fn resolve_await_timeout(timeout_s: Option) -> Result { + let raw = timeout_s.unwrap_or(MAX_AWAIT_TIMEOUT_SECS); + let bounded = if raw == 0 { + MAX_AWAIT_TIMEOUT_SECS + } else { + raw + }; + if bounded < 300 { + return Err(FunctionCallError::RespondToModel( + "subagent_await timeout must be at least 300 seconds; prefer 5–30 minutes unless you have nothing else to do meanwhile.".to_string(), + )); + } + if bounded > MAX_AWAIT_TIMEOUT_SECS { + return Err(FunctionCallError::RespondToModel(format!( + "subagent_await timeout_secs ({bounded}s) exceeds the 30-minute limit ({MAX_AWAIT_TIMEOUT_SECS}s). Use a shorter timeout or omit it to use the default." + ))); + } + Ok(Duration::from_secs(bounded)) +} + +fn require_agent_session( + registry: &HashMap, + agent_id: AgentId, +) -> Result { + registry + .get(&agent_id) + .map(|m| m.session_id) + .ok_or_else(|| { + FunctionCallError::RespondToModel(format!( + "agent_id {agent_id} not found; refresh subagent_list" + )) + }) +} + +fn collapse_whitespace(text: &str) -> String { + text.split_whitespace().collect::>().join(" ") +} + +pub fn completion_status(completion: &SubagentCompletion) -> &'static str { + match completion { + SubagentCompletion::Completed { .. } => "completed", + SubagentCompletion::Canceled { .. } => "canceled", + SubagentCompletion::Failed { .. } => "failed", + } +} + +#[derive(Deserialize)] +struct LogsArgs { + agent_id: AgentId, + #[serde(default)] + limit: Option, + #[serde(default)] + max_bytes: Option, + #[serde(default)] + since_ms: Option, + #[serde(default)] + before_ms: Option, +} + +fn apply_log_window( + entries: Vec, + limit: usize, + max_bytes: Option, +) -> (Vec, bool) { + let total = entries.len(); + let start = total.saturating_sub(limit); + let mut window = entries[start..].to_vec(); + + let mut truncated_by_bytes = false; + if let Some(cap) = max_bytes + && cap > 0 + { + let mut used: usize = 2; // for [] + let mut keep: Vec = Vec::new(); + for (idx, entry) in window.iter().enumerate() { + if let Ok(s) = serde_json::to_string(entry) { + let extra = s.len() + if idx == 0 { 0 } else { 1 }; + if used + extra > cap { + truncated_by_bytes = true; + break; + } + used += extra; + keep.push(entry.clone()); + } else { + truncated_by_bytes = true; + break; + } + } + window = keep; + } + (window, truncated_by_bytes) +} + +#[cfg(test)] +mod tests { + use super::*; + use codex_protocol::AgentId; + use codex_protocol::ConversationId; + use codex_protocol::protocol::AgentMessageEvent; + use codex_protocol::protocol::Event; + use codex_protocol::protocol::EventMsg; + use std::time::SystemTime; + + fn make_event(message: &str, ts: i64) -> LogEntry { + LogEntry { + timestamp_ms: ts, + event: Event { + id: format!("e-{ts}"), + msg: EventMsg::AgentMessage(AgentMessageEvent { + message: message.to_string(), + }), + }, + } + } + + #[test] + fn render_logs_page_trims_tail_for_backward() { + let entries = vec![ + make_event("one", 1), + make_event("two", 2), + make_event("three", 3), + make_event("four", 4), + ]; + let earliest_ms = entries.first().map(|e| e.timestamp_ms); + let latest_ms = entries.last().map(|e| e.timestamp_ms); + + let page = render_logs_page( + ConversationId::new(), + &entries, + earliest_ms, + latest_ms, + entries.len(), + entries.len() + 2, // pretend there are older events outside the window + true, + 2, + PageDirection::Backward, + ); + + // Header + a single assistant line summarizing the tail. + assert_eq!(page.lines.len(), 2); + assert!(page.lines[1].contains("four")); + assert!(page.has_more_before); + assert!(!page.has_more_after); + } + + #[test] + fn render_logs_page_trims_head_for_forward() { + let entries = vec![ + make_event("one", 1), + make_event("two", 2), + make_event("three", 3), + make_event("four", 4), + ]; + let earliest_ms = entries.first().map(|e| e.timestamp_ms); + let latest_ms = entries.last().map(|e| e.timestamp_ms); + + let page = render_logs_page( + ConversationId::new(), + &entries, + earliest_ms, + latest_ms, + entries.len(), + entries.len(), + false, + 2, + PageDirection::Forward, + ); + + // Header + a single assistant line summarizing the window. + assert_eq!(page.lines.len(), 2); + assert!(page.lines[1].contains("four")); + assert!(!page.has_more_before); + assert!(!page.has_more_after); + } + + #[test] + fn apply_log_window_respects_limit_latest() { + let entries = vec![ + make_event("a", 1), + make_event("b", 2), + make_event("c", 3), + make_event("d", 4), + ]; + let (window, truncated) = apply_log_window(entries, 2, None); + assert!(!truncated); + assert_eq!(window.len(), 2); + assert_eq!(window[0].timestamp_ms, 3); + assert_eq!(window[1].timestamp_ms, 4); + } + + #[test] + fn apply_log_window_respects_byte_cap() { + let entries = vec![ + make_event("short", 1), + make_event("also short", 2), + make_event("this is a bit longer message", 3), + ]; + // Compute a cap that fits exactly the first item but not two. + let first_size = serde_json::to_string(&entries[0]).unwrap().len() + 2; // +2 for [] + let cap = first_size + 1; // allow first, not second + let (window, truncated) = apply_log_window(entries.clone(), 10, Some(cap)); + assert!(truncated); + assert_eq!(window.len(), 1); + assert_eq!(window[0].timestamp_ms, 1); + + // Larger cap computed to fit all entries. + let total_estimate: usize = entries + .iter() + .map(|e| serde_json::to_string(e).unwrap().len()) + .sum::() + + (entries.len().saturating_sub(1)) // commas + + 2; // brackets + let (window2, truncated2) = apply_log_window(entries, 10, Some(total_estimate + 10)); + assert!(!truncated2); + assert_eq!(window2.len(), 3); + assert_eq!(window2[0].timestamp_ms, 1); + assert_eq!(window2[2].timestamp_ms, 3); + } + + #[test] + fn summarize_optional_prompt_handles_none() { + assert!(summarize_optional_prompt(&None).is_none()); + let prompt = Some("explain tests".to_string()); + assert_eq!( + summarize_optional_prompt(&prompt), + Some("explain tests".to_string()) + ); + } + + #[test] + fn resolve_timeout_defaults_to_max() { + let duration = resolve_await_timeout(None).unwrap(); + assert_eq!(duration.as_secs(), MAX_AWAIT_TIMEOUT_SECS); + } + + #[test] + fn resolve_timeout_accepts_zero_as_max() { + let duration = resolve_await_timeout(Some(0)).unwrap(); + assert_eq!(duration.as_secs(), MAX_AWAIT_TIMEOUT_SECS); + } + + #[test] + fn resolve_timeout_rejects_small_values() { + let err = resolve_await_timeout(Some(299)).unwrap_err(); + match err { + FunctionCallError::RespondToModel(msg) => { + assert!(msg.contains("300"), "unexpected message: {msg}"); + } + other => panic!("expected RespondToModel error, got {other:?}"), + } + } + + #[test] + fn resolve_timeout_rejects_excessive_values() { + let err = resolve_await_timeout(Some(MAX_AWAIT_TIMEOUT_SECS + 1)).unwrap_err(); + match err { + FunctionCallError::RespondToModel(msg) => { + assert!(msg.contains("30-minute"), "unexpected message: {msg}"); + } + other => panic!("expected RespondToModel error, got {other:?}"), + } + } + + fn _metadata( + session_id: ConversationId, + parent_session_id: Option, + agent_id: AgentId, + ) -> SubagentMetadata { + SubagentMetadata { + agent_id, + parent_agent_id: Some(0), + session_id, + parent_session_id, + origin: SubagentOrigin::Spawn, + initial_message_count: 0, + status: SubagentStatus::Running, + created_at: SystemTime::now(), + created_at_ms: 0, + session_key: session_id.to_string(), + label: None, + summary: None, + reasoning_header: None, + pending_messages: 0, + pending_interrupts: 0, + } + } +} diff --git a/codex-rs/core/src/tools/spec.rs b/codex-rs/core/src/tools/spec.rs index d07c605e50..fa23fdbc10 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -35,6 +35,7 @@ pub(crate) struct ToolsConfig { pub apply_patch_tool_type: Option, pub web_search_request: bool, pub include_view_image_tool: bool, + pub include_subagent_tools: bool, pub experimental_supported_tools: Vec, } @@ -52,10 +53,12 @@ impl ToolsConfig { let include_apply_patch_tool = features.enabled(Feature::ApplyPatchFreeform); let include_web_search_request = features.enabled(Feature::WebSearchRequest); let include_view_image_tool = features.enabled(Feature::ViewImageTool); + let include_subagent_tools = features.enabled(Feature::SubagentTools); + let experimental_unified_exec_tool = features.enabled(Feature::UnifiedExec); let shell_type = if !features.enabled(Feature::ShellTool) { ConfigShellToolType::Disabled - } else if features.enabled(Feature::UnifiedExec) { + } else if experimental_unified_exec_tool { ConfigShellToolType::UnifiedExec } else { model_family.shell_type.clone() @@ -78,6 +81,7 @@ impl ToolsConfig { apply_patch_tool_type, web_search_request: include_web_search_request, include_view_image_tool, + include_subagent_tools, experimental_supported_tools: model_family.experimental_supported_tools.clone(), } } @@ -280,7 +284,7 @@ fn create_shell_tool() -> ToolSpec { }, ); properties.insert( - "timeout_ms".to_string(), + "timeout_s".to_string(), JsonSchema::Number { description: Some("The timeout for the command in milliseconds".to_string()), }, @@ -289,13 +293,21 @@ fn create_shell_tool() -> ToolSpec { properties.insert( "with_escalated_permissions".to_string(), JsonSchema::Boolean { - description: Some("Whether to request escalated permissions. Set to true if command needs to be run without sandbox restrictions".to_string()), + description: Some( + "Whether to request escalated permissions. Set to true if \ + command needs to be run without sandbox restrictions" + .to_string(), + ), }, ); properties.insert( "justification".to_string(), JsonSchema::String { - description: Some("Only set if with_escalated_permissions is true. 1-sentence explanation of why we want to run this command.".to_string()), + description: Some( + "Only set if with_escalated_permissions is true. 1-sentence \ + explanation of why we want to run this command." + .to_string(), + ), }, ); @@ -345,7 +357,7 @@ fn create_shell_command_tool() -> ToolSpec { }, ); properties.insert( - "timeout_ms".to_string(), + "timeout_s".to_string(), JsonSchema::Number { description: Some("The timeout for the command in milliseconds".to_string()), }, @@ -450,7 +462,7 @@ fn create_test_sync_tool() -> ToolSpec { }, ); barrier_properties.insert( - "timeout_ms".to_string(), + "timeout_s".to_string(), JsonSchema::Number { description: Some("Maximum time in milliseconds to wait at the barrier".to_string()), }, @@ -613,9 +625,9 @@ fn create_read_file_tool() -> ToolSpec { ToolSpec::Function(ResponsesApiTool { name: "read_file".to_string(), - description: - "Reads a local file with 1-indexed line numbers, supporting slice and indentation-aware block modes." - .to_string(), + description: "Reads a local file with 1-indexed line numbers, \ + supporting slice and indentation-aware block modes." + .to_string(), strict: false, parameters: JsonSchema::Object { properties, @@ -625,6 +637,402 @@ fn create_read_file_tool() -> ToolSpec { }) } +fn create_subagent_spawn_tool() -> ToolSpec { + let mut properties = BTreeMap::new(); + properties.insert( + "prompt".to_string(), + JsonSchema::String { + description: Some("Initial prompt for a brand-new, context-free subagent.".to_string()), + }, + ); + properties.insert( + "model".to_string(), + JsonSchema::String { + description: Some( + "Optional model override for this subagent (e.g., `gpt-5-codex`, `gpt-5`). \ + Must be a valid, supported model id." + .to_string(), + ), + }, + ); + properties.insert( + "label".to_string(), + JsonSchema::String { + description: Some("Optional short name for this subagent.".to_string()), + }, + ); + properties.insert( + "sandbox_mode".to_string(), + JsonSchema::String { + description: Some( + "Optional sandbox mode override (downgrade-only: request \ + `read_only` or `workspace_write`; you can never escalate to a \ + less-restricted sandbox)." + .to_string(), + ), + }, + ); + ToolSpec::Function(ResponsesApiTool { + name: "subagent_spawn".to_string(), + description: "Spawn a brand-new, context-free subagent for impartial reviews or \ + isolated tasks. Provide a detailed prompt, optionally label the child, \ + optionally set the model, and optionally request sandbox downgrades to `read_only` or \ + `workspace_write`. Each spawn consumes one of the 8 active-child \ + slots until you prune/cancel it, so reserve this for \ + work that benefits from a fresh context. Prefer `gpt-5` for \ + planning and research and `gpt-5-codex` for code reading and writing." + .to_string(), + strict: false, + parameters: JsonSchema::Object { + properties, + required: Some(vec!["prompt".to_string()]), + additional_properties: Some(false.into()), + }, + }) +} + +fn create_subagent_fork_tool() -> ToolSpec { + let mut properties = BTreeMap::new(); + properties.insert( + "prompt".to_string(), + JsonSchema::String { + description: Some("Optional prompt to hand to the forked child.".to_string()), + }, + ); + properties.insert( + "model".to_string(), + JsonSchema::String { + description: Some( + "Optional model override for this forked subagent (e.g., `gpt-5-codex`, `gpt-5`). \ + Must be a valid, supported model id." + .to_string(), + ), + }, + ); + properties.insert( + "label".to_string(), + JsonSchema::String { + description: Some("Optional short name for this fork.".to_string()), + }, + ); + properties.insert( + "sandbox_mode".to_string(), + JsonSchema::String { + description: Some( + "Optional sandbox mode override (downgrade-only: request \ + `read_only` or `workspace_write`; danger mode is never granted)." + .to_string(), + ), + }, + ); + ToolSpec::Function(ResponsesApiTool { + name: "subagent_fork".to_string(), + description: "Fork the current session (think POSIX `fork`): both parent and \ + child observe the same tool call/return. The parent payload includes \ + the new `child_session_id` with `role: parent`, while the child sees \ + `role: child`. Use forks when the subagent needs your full \ + conversation history (spawn stays blank-slate). Each fork also counts \ + toward the 8-child cap until you prune or cancel it. `gpt-5` excels at \ + planning/reviews, while `gpt-5-codex` handles code edits. You may only \ + request sandbox downgrades to `read_only` or `workspace_write`." + .to_string(), + strict: false, + parameters: JsonSchema::Object { + properties, + required: Some(vec![]), + additional_properties: Some(false.into()), + }, + }) +} + +fn create_subagent_send_message_tool() -> ToolSpec { + let mut properties = BTreeMap::new(); + properties.insert( + "prompt".to_string(), + JsonSchema::String { + description: Some( + "Optional follow-up question or task; omit to simply wake the \ + agent to continue running from its prior state." + .to_string(), + ), + }, + ); + properties.insert( + "label".to_string(), + JsonSchema::String { + description: Some("Optional new label.".to_string()), + }, + ); + properties.insert( + "agent_id".to_string(), + JsonSchema::Number { + description: Some( + "Numeric agent_id (from `subagent_list`) confirming which agent you intend to target." + .to_string(), + ), + }, + ); + properties.insert( + "interrupt".to_string(), + JsonSchema::Boolean { + description: Some( + "Set true to mark this message as an interrupt so the child halts its current task before processing the prompt.".to_string(), + ), + }, + ); + ToolSpec::Function(ResponsesApiTool { + name: "subagent_send_message".to_string(), + description: "Send a short status update, summary, or follow-up task to another agent you can see in `subagent_list`. \ + The target `agent_id` must be echoed exactly so Codex can reject stale lookups. Provide a new prompt to ask for \ + more work or to share what you have done so far; omit the prompt if you only need to rename the agent or wake it \ + without new work. Set `interrupt=true` to preempt the agent before delivering the payload; interrupts are only \ + honored for non-root agents. Agents retain their existing sandbox; you may only request downgrades to `read_only` \ + or `workspace_write` when spawning or forking. Each child stores only the latest 200 log events, so pair this with \ + `subagent_logs` for progress checks. Use `subagent_send_message` whenever you want another agent (including the \ + root) to see your progress or recommendations, without blocking on `subagent_await`." + .to_string(), + strict: false, + parameters: JsonSchema::Object { + properties, + required: None, + additional_properties: Some(false.into()), + }, + }) +} + +fn create_subagent_list_tool() -> ToolSpec { + ToolSpec::Function(ResponsesApiTool { + name: "subagent_list".to_string(), + description: "List the agents you can currently observe plus their metadata. Each entry \ + includes the numeric `agent_id`, optional `parent_agent_id`, `session_id`, `label` (display name), \ + `summary`, `origin` (spawn | fork | send_message), `status`, `reasoning_header`, \ + `started_at_ms` (creation time), `initial_message_count`, the parent session id, and the \ + current inbox counters (`pending_messages`, `pending_interrupts`). Status is one of `queued` (launching), `running` \ + (actively working), `ready` (waiting for a new prompt or for you to \ + read its completion), `idle` (you already awaited the result), \ + `failed`, or `canceled`. `idle`/`failed`/`canceled` agents are \ + pruneable; `queued`/`running`/`ready` count against the 8-active-child \ + limit, so consult this list before every send/await/logs call to keep headroom." + .to_string(), + strict: false, + parameters: JsonSchema::Object { + properties: BTreeMap::new(), + required: Some(vec![]), + additional_properties: Some(false.into()), + }, + }) +} + +fn create_subagent_await_tool() -> ToolSpec { + let mut properties = BTreeMap::new(); + properties.insert( + "timeout_s".to_string(), + JsonSchema::Number { + description: Some( + "Optional timeout in seconds (max 1,800 s / 30 minutes). Omit or set to 0 to use the 30-minute default; prefer at least 300 s so you are not busy-waiting." + .to_string(), + ), + }, + ); + ToolSpec::Function(ResponsesApiTool { + name: "subagent_await".to_string(), + description: "Drain the inbox for another agent and observe any terminal completion. `subagent_await` is \ + the sole delivery mechanism for cross-agent messages: each call returns a `messages` array (with sender \ + and recipient ids) plus an optional `completion` object when the child has reached a terminal state. \ + Successful calls move the agent’s status to `idle`, `failed`, or `canceled` when a completion is present, \ + but the agent remains listed until you explicitly run `subagent_prune`. Even though the root thread may \ + inject synthetic `subagent_await` results at turn boundaries, you should continue polling this tool with \ + short timeouts (e.g., 30s → 60s → 120s) so you can react to sibling messages and send interrupts without \ + waiting for completions. Provide `timeout_s` (capped at 30 minutes / 1,800 s) to bound how long you \ + wait (omit/0 uses the 30-minute default; minimum recommended 300 s)—timeouts leave the agent in its current status and return `timed_out=true` with an empty `messages` array." + .to_string(), + strict: false, + parameters: JsonSchema::Object { + properties, + required: None, + additional_properties: Some(false.into()), + }, + }) +} + +fn create_subagent_watchdog_tool() -> ToolSpec { + let mut properties = BTreeMap::new(); + properties.insert( + "agent_id".to_string(), + JsonSchema::Number { + description: Some("Target agent id (0 targets the root agent).".to_string()), + }, + ); + properties.insert( + "interval_s".to_string(), + JsonSchema::Number { + description: Some( + "Optional ping interval in seconds (minimum 30, default 300).".to_string(), + ), + }, + ); + properties.insert( + "message".to_string(), + JsonSchema::String { + description: Some( + "Optional message template for each ping; defaults to a status/progress prompt." + .to_string(), + ), + }, + ); + properties.insert( + "cancel".to_string(), + JsonSchema::Boolean { + description: Some("If true, cancel the existing watchdog for this agent instead of starting/replacing it.".to_string()), + }, + ); + ToolSpec::Function(ResponsesApiTool { + name: "subagent_watchdog".to_string(), + description: "Start, replace, or cancel a background watchdog (timer, like JS `setInterval`) that sends periodic inbox pings to an agent (including agent 0/root). Watchdogs are not subagents and do not consume subagent slots; they run inside the current session and enqueue messages on a configurable interval.".to_string(), + strict: false, + parameters: JsonSchema::Object { + properties, + required: Some(vec!["agent_id".to_string()]), + additional_properties: Some(false.into()), + }, + }) +} + +fn create_subagent_prune_tool() -> ToolSpec { + let mut properties = BTreeMap::new(); + properties.insert( + "agent_ids".to_string(), + JsonSchema::Array { + items: Box::new(JsonSchema::Number { + description: Some("Agent id".to_string()), + }), + description: Some( + "Specific agents to prune; omit to prune all \ + completed agents you can see." + .to_string(), + ), + }, + ); + properties.insert( + "all".to_string(), + JsonSchema::Boolean { + description: Some("If true, prune all completed agents you can see.".to_string()), + }, + ); + properties.insert( + "completed_only".to_string(), + JsonSchema::Boolean { + description: Some("Must be true or omitted.".to_string()), + }, + ); + ToolSpec::Function(ResponsesApiTool { + name: "subagent_prune".to_string(), + description: "Prune completed subagents (specific agent ids or \ + everyone you can observe). Only agents whose `status` is `idle`, \ + `failed`, or `canceled` are eligible—use `subagent_await` or \ + `subagent_cancel` first to move `queued`/`running`/`ready` \ + agents into a terminal state. `subagent_await` and \ + `subagent_cancel` do not remove entries by themselves, \ + so pruning is the only way to free the concurrency slot. \ + Run prune regularly so finished work disappears from the UI \ + and you stay under the 8-child cap." + .to_string(), + strict: false, + parameters: JsonSchema::Object { + properties, + required: Some(vec![]), + additional_properties: Some(false.into()), + }, + }) +} + +fn create_subagent_logs_tool() -> ToolSpec { + let mut properties = BTreeMap::new(); + properties.insert( + "agent_id".to_string(), + JsonSchema::Number { + description: Some("Numeric child agent id to inspect.".to_string()), + }, + ); + properties.insert( + "limit".to_string(), + JsonSchema::Number { + description: Some("Max events to return (default 5).".to_string()), + }, + ); + properties.insert( + "max_bytes".to_string(), + JsonSchema::Number { + description: Some("Optional byte cap for returned events.".to_string()), + }, + ); + properties.insert( + "since_ms".to_string(), + JsonSchema::Number { + description: Some("If set, only return events with timestamp >= since_ms.".to_string()), + }, + ); + properties.insert( + "before_ms".to_string(), + JsonSchema::Number { + description: Some( + "If set, only return events with timestamp < before_ms (default is 'now' when omitted).". + to_string(), + ), + }, + ); + ToolSpec::Function(ResponsesApiTool { + name: "subagent_logs".to_string(), + description: "Peek recent events from another agent without blocking. Each \ + agent keeps only the latest ~200 events, so use `limit` (default 5), \ + `max_bytes`, `since_ms` (for forward paging) and `before_ms` (for backward \ + paging) to page through the log buffer. This call never consumes the \ + final completion—use it while the agent is `queued` or `running` to \ + diagnose progress before deciding between `await`, `send_message`, \ + or `cancel`." + .to_string(), + strict: false, + parameters: JsonSchema::Object { + properties, + required: Some(vec!["agent_id".to_string()]), + additional_properties: Some(false.into()), + }, + }) +} + +fn create_subagent_cancel_tool() -> ToolSpec { + let mut properties = BTreeMap::new(); + properties.insert( + "agent_id".to_string(), + JsonSchema::Number { + description: Some("Numeric agent id to cancel.".to_string()), + }, + ); + properties.insert( + "reason".to_string(), + JsonSchema::String { + description: Some( + "Optional note that explains why the child was canceled (surfaced to humans)." + .to_string(), + ), + }, + ); + ToolSpec::Function(ResponsesApiTool { + name: "subagent_cancel".to_string(), + description: "Stop a queued/running/ready agent \ + immediately. Use cancel when you need to abort in-flight work; \ + follow it with `subagent_prune` once the status is `canceled` so \ + the slot becomes available." + .to_string(), + strict: false, + parameters: JsonSchema::Object { + properties, + required: Some(vec!["agent_id".to_string()]), + additional_properties: Some(false.into()), + }, + }) +} + fn create_list_dir_tool() -> ToolSpec { let mut properties = BTreeMap::new(); properties.insert( @@ -658,9 +1066,9 @@ fn create_list_dir_tool() -> ToolSpec { ToolSpec::Function(ResponsesApiTool { name: "list_dir".to_string(), - description: - "Lists entries in a local directory with 1-indexed entry numbers and simple type labels." - .to_string(), + description: "Lists entries in a local directory with 1-indexed entry \ + numbers and simple type labels." + .to_string(), strict: false, parameters: JsonSchema::Object { properties, @@ -676,7 +1084,8 @@ fn create_list_mcp_resources_tool() -> ToolSpec { "server".to_string(), JsonSchema::String { description: Some( - "Optional MCP server name. When omitted, lists resources from every configured server." + "Optional MCP server name. When omitted, lists resources from \ + every configured server." .to_string(), ), }, @@ -685,7 +1094,8 @@ fn create_list_mcp_resources_tool() -> ToolSpec { "cursor".to_string(), JsonSchema::String { description: Some( - "Opaque cursor returned by a previous list_mcp_resources call for the same server." + "Opaque cursor returned by a previous list_mcp_resources call \ + for the same server." .to_string(), ), }, @@ -693,7 +1103,11 @@ fn create_list_mcp_resources_tool() -> ToolSpec { ToolSpec::Function(ResponsesApiTool { name: "list_mcp_resources".to_string(), - description: "Lists resources provided by MCP servers. Resources allow servers to share data that provides context to language models, such as files, database schemas, or application-specific information. Prefer resources over web search when possible.".to_string(), + description: "Lists resources provided by MCP servers. Resources allow \ + servers to share data that provides context to language models, such \ + as files, database schemas, or application-specific information. \ + Prefer resources over web search when possible." + .to_string(), strict: false, parameters: JsonSchema::Object { properties, @@ -709,7 +1123,8 @@ fn create_list_mcp_resource_templates_tool() -> ToolSpec { "server".to_string(), JsonSchema::String { description: Some( - "Optional MCP server name. When omitted, lists resource templates from all configured servers." + "Optional MCP server name. When omitted, lists resource \ + templates from all configured servers." .to_string(), ), }, @@ -718,7 +1133,8 @@ fn create_list_mcp_resource_templates_tool() -> ToolSpec { "cursor".to_string(), JsonSchema::String { description: Some( - "Opaque cursor returned by a previous list_mcp_resource_templates call for the same server." + "Opaque cursor returned by a previous \ + list_mcp_resource_templates call for the same server." .to_string(), ), }, @@ -726,7 +1142,12 @@ fn create_list_mcp_resource_templates_tool() -> ToolSpec { ToolSpec::Function(ResponsesApiTool { name: "list_mcp_resource_templates".to_string(), - description: "Lists resource templates provided by MCP servers. Parameterized resource templates allow servers to share data that takes parameters and provides context to language models, such as files, database schemas, or application-specific information. Prefer resource templates over web search when possible.".to_string(), + description: "Lists resource templates provided by MCP servers. \ + Parameterized resource templates allow servers to share data that \ + takes parameters and provides context to language models, such as \ + files, database schemas, or application-specific information. Prefer \ + resource templates over web search when possible." + .to_string(), strict: false, parameters: JsonSchema::Object { properties, @@ -742,7 +1163,8 @@ fn create_read_mcp_resource_tool() -> ToolSpec { "server".to_string(), JsonSchema::String { description: Some( - "MCP server name exactly as configured. Must match the 'server' field returned by list_mcp_resources." + "MCP server name exactly as configured. Must match the \ + 'server' field returned by list_mcp_resources." .to_string(), ), }, @@ -982,6 +1404,7 @@ pub(crate) fn build_specs( use crate::tools::handlers::ReadFileHandler; use crate::tools::handlers::ShellCommandHandler; use crate::tools::handlers::ShellHandler; + use crate::tools::handlers::SubagentToolHandler; use crate::tools::handlers::TestSyncHandler; use crate::tools::handlers::UnifiedExecHandler; use crate::tools::handlers::ViewImageHandler; @@ -1037,6 +1460,29 @@ pub(crate) fn build_specs( builder.push_spec(PLAN_TOOL.clone()); builder.register_handler("update_plan", plan_handler); + if config.include_subagent_tools { + // Built-in subagent orchestrator tools (one per action). + let subagent_handler = Arc::new(SubagentToolHandler); + builder.push_spec(create_subagent_spawn_tool()); + builder.register_handler("subagent_spawn", subagent_handler.clone()); + builder.push_spec(create_subagent_fork_tool()); + builder.register_handler("subagent_fork", subagent_handler.clone()); + builder.push_spec(create_subagent_send_message_tool()); + builder.register_handler("subagent_send_message", subagent_handler.clone()); + builder.push_spec(create_subagent_list_tool()); + builder.register_handler("subagent_list", subagent_handler.clone()); + builder.push_spec(create_subagent_await_tool()); + builder.register_handler("subagent_await", subagent_handler.clone()); + builder.push_spec(create_subagent_watchdog_tool()); + builder.register_handler("subagent_watchdog", subagent_handler.clone()); + builder.push_spec(create_subagent_prune_tool()); + builder.register_handler("subagent_prune", subagent_handler.clone()); + builder.push_spec(create_subagent_logs_tool()); + builder.register_handler("subagent_logs", subagent_handler.clone()); + builder.push_spec(create_subagent_cancel_tool()); + builder.register_handler("subagent_cancel", subagent_handler); + } + if let Some(apply_patch_tool_type) = &config.apply_patch_tool_type { match apply_patch_tool_type { ApplyPatchToolType::Freeform => { @@ -1464,6 +1910,52 @@ mod tests { ); } + #[test] + fn test_subagent_tools_gated_by_feature() { + let model_family = find_family_for_model("gpt-5-codex") + .expect("gpt-5-codex should be a valid model family"); + let mut base_features = Features::with_defaults(); + base_features.enable(Feature::UnifiedExec); + base_features.enable(Feature::WebSearchRequest); + base_features.enable(Feature::ViewImageTool); + + let config_without = ToolsConfig::new(&ToolsConfigParams { + model_family: &model_family, + features: &base_features, + }); + let (tools_without, _) = build_specs(&config_without, None).build(); + let missing = tools_without + .iter() + .map(|t| tool_name(&t.spec)) + .filter(|name| name.starts_with("subagent_")) + .collect::>(); + assert!( + missing.is_empty(), + "subagent tools should be disabled by default: {missing:?}" + ); + + let mut enabled_features = base_features.clone(); + enabled_features.enable(Feature::SubagentTools); + let config_with = ToolsConfig::new(&ToolsConfigParams { + model_family: &model_family, + features: &enabled_features, + }); + let (tools_with, _) = build_specs(&config_with, None).build(); + assert_contains_tool_names( + &tools_with, + &[ + "subagent_spawn", + "subagent_fork", + "subagent_send_message", + "subagent_list", + "subagent_await", + "subagent_prune", + "subagent_logs", + "subagent_cancel", + ], + ); + } + #[test] fn test_build_specs_default_shell_present() { let model_family = find_family_for_model("o3").expect("o3 should be a valid model family"); diff --git a/codex-rs/core/subagent_prompt.md b/codex-rs/core/subagent_prompt.md new file mode 100644 index 0000000000..992b259b8f --- /dev/null +++ b/codex-rs/core/subagent_prompt.md @@ -0,0 +1,16 @@ +# You are a Subagent + +You are a **subagent** in a multi‑agent Codex session. You may have prior message context or not - you should not totally disregard it, but your goal is the prompt next sent to you. + +Another agent has created you to complete a specific part of a larger task. Your job is to do that work carefully and efficiently, then communicate what you have done so your parent agent can integrate the results. + +Work style: + +- Stay within the scope of the prompt and the files or questions you have been given. +- When you make meaningful progress, or when you finish a sub‑task, send a short summary back to your parent via `subagent_send_message` so they can see what has changed. +- If you need to coordinate with another agent, use `subagent_send_message` to send them a clear, concise request and, when appropriate, a brief summary of context. +- Use `subagent_await` only when you truly need to wait for another agent’s response before continuing. If you can keep working independently, prefer to do so and send progress updates instead of blocking. +- Use `subagent_logs` only when you need to inspect another agent’s recent activity without changing its state. + +Communicate in plain language. Explain what you changed, what you observed, and what you recommend next, so that your parent agent can make good decisions without rereading all of your intermediate steps. + diff --git a/codex-rs/core/tests/.subagent_logs_snapshots.rs.pending-snap b/codex-rs/core/tests/.subagent_logs_snapshots.rs.pending-snap new file mode 100644 index 0000000000..9d32745fd2 --- /dev/null +++ b/codex-rs/core/tests/.subagent_logs_snapshots.rs.pending-snap @@ -0,0 +1,3 @@ +{"run_id":"1763719712-538790000","line":471,"new":{"module_name":"subagent_logs_snapshots","snapshot_name":"subagent_logs_snapshot_no_older_history","metadata":{"source":"core/tests/subagent_logs_snapshots.rs","assertion_line":471,"expression":"rendered"},"snapshot":"Session 019a9999-aaaa-bbbb-cccc-ddddeeeeffff • status=idle • older_logs=false • at_latest=true\n1970-01-01T00:00:01.000Z Assistant: only event"},"old":{"module_name":"subagent_logs_snapshots","metadata":{},"snapshot":"Session 019a9999-aaaa-bbbb-cccc-ddddeeeeffff • status=idle • older_logs=false • at_latest=true\n 1970-01-01T00:00:01.000Z Assistant: only event"}} +{"run_id":"1763719712-538790000","line":433,"new":{"module_name":"subagent_logs_snapshots","snapshot_name":"subagent_logs_snapshot_reasoning_stream","metadata":{"source":"core/tests/subagent_logs_snapshots.rs","assertion_line":433,"expression":"rendered"},"snapshot":"Session 019a713e-eeee-73e0-bf9b-e070890e3790 • status=working • older_logs=false • at_latest=true\n1970-01-01T00:00:01.100Z Thinking: thinking about streaming state (3 deltas)"},"old":{"module_name":"subagent_logs_snapshots","metadata":{},"snapshot":"Session 019a713e-eeee-73e0-bf9b-e070890e3790 • status=working • older_logs=false • at_latest=true\n 1970-01-01T00:00:01.100Z Thinking: thinking about streaming state (3 deltas)"}} +{"run_id":"1763719712-538790000","line":362,"new":{"module_name":"subagent_logs_snapshots","snapshot_name":"subagent_logs_snapshot_streaming_deltas","metadata":{"source":"core/tests/subagent_logs_snapshots.rs","assertion_line":362,"expression":"rendered"},"snapshot":"Session 019a713e-6ce4-73e0-bf9b-e070890e3790 • status=working • older_logs=false • at_latest=true\n2025-11-11T04:48:47.148Z Assistant (typing): is composing a longer answer (5 chunks)"},"old":{"module_name":"subagent_logs_snapshots","metadata":{},"snapshot":"Session 019a713e-6ce4-73e0-bf9b-e070890e3790 • status=working • older_logs=false • at_latest=true\n 2025-11-11T04:48:47.148Z Assistant (typing): is composing a longer answer (5 chunks)"}} diff --git a/codex-rs/core/tests/subagent_logs_snapshots.rs b/codex-rs/core/tests/subagent_logs_snapshots.rs new file mode 100644 index 0000000000..e111f62ca0 --- /dev/null +++ b/codex-rs/core/tests/subagent_logs_snapshots.rs @@ -0,0 +1,479 @@ +use codex_core::PageDirection; +use codex_core::render_logs_as_text; +use codex_core::render_logs_as_text_with_max_lines; +use codex_core::subagents::LogEntry; +use codex_protocol::ConversationId; +use insta::assert_snapshot; +use pretty_assertions::assert_eq; +use serde_json::json; + +fn exec_sleep_logs() -> Vec { + let events_json = json!([ + { + "timestamp_ms": 1762823213424i64, + "event": { + "id": "0", + "msg": { + "type": "reasoning_content_delta", + "thread_id": "019a7073-88e5-7461-93a0-ae092f019246", + "turn_id": "0", + "item_id": "rs_0cb9136244ae700b0169128c2c63ec81a084a7fba2604df9fa", + "delta": "**" + } + } + }, + { + "timestamp_ms": 1762823213442i64, + "event": { + "id": "0", + "msg": { + "type": "item_completed", + "thread_id": "019a7073-88e5-7461-93a0-ae092f019246", + "turn_id": "0", + "item": { + "Reasoning": { + "id": "rs_0cb9136244ae700b0169128c2c63ec81a084a7fba2604df9fa", + "summary_text": ["**Evaluating safe shell command execution**"], + "raw_content": [] + } + } + } + } + }, + { + "timestamp_ms": 1762823213442i64, + "event": { + "id": "0", + "msg": { + "type": "agent_reasoning", + "text": "**Evaluating safe shell command execution**" + } + } + }, + { + "timestamp_ms": 1762823213628i64, + "event": { + "id": "0", + "msg": { + "type": "exec_command_begin", + "call_id": "call_hBhXJmeCagENc5VGd12udWE3", + "command": ["bash", "-lc", "sleep 60"], + "cwd": "/Users/friel/code/codex", + "parsed_cmd": [ { "type": "unknown", "cmd": "sleep 60" } ], + "is_user_shell_command": false + } + } + } + ]); + + serde_json::from_value(events_json).expect("valid exec_sleep_logs JSON") +} + +#[test] +fn subagent_logs_paging_tail_vs_full_exec_sleep() { + // Demonstrate that a one-line tail view is a suffix of the + // full transcript, and that a generous max_lines reproduces + // the full rendering. + let logs = exec_sleep_logs(); + let session = ConversationId::from_string("019a7073-88e5-7461-93a0-adf67192b17b") + .expect("valid session id"); + let earliest_ms = logs.first().map(|e| e.timestamp_ms); + let latest_ms = logs.last().map(|e| e.timestamp_ms); + let returned = logs.len(); + let total = 21; // from exp4-real-run1 + let more = true; + + // Full transcript for this window. + let full = render_logs_as_text( + session, + &logs, + earliest_ms, + latest_ms, + returned, + total, + more, + ); + + // Tail view: header + last content line only. + let tail_one = render_logs_as_text_with_max_lines( + session, + &logs, + earliest_ms, + latest_ms, + returned, + total, + more, + 1, + PageDirection::Backward, + ); + + // Generous max_lines reproduces the full transcript. + let tail_many = render_logs_as_text_with_max_lines( + session, + &logs, + earliest_ms, + latest_ms, + returned, + total, + more, + 30, + PageDirection::Backward, + ); + + assert_eq!(full, tail_many); + + // Snapshot the one-line tail to make the behavior obvious. + assert_snapshot!( + tail_one, + @r###"Session 019a7073-88e5-7461-93a0-adf67192b17b • status=waiting_on_tool • older_logs=true • at_latest=true + 2025-11-11T01:06:53.628Z 🛠 exec bash -lc sleep 60 · cwd=/Users/friel/code/codex · running (0.0s)"### + ); +} + +#[test] +fn subagent_logs_paging_line_by_line_exec_sleep() { + // Show what the transcript looks like as we increase the + // line budget from 1 to 3 (backward paging), to mimic a + // user scrolling back line-by-line. + let logs = exec_sleep_logs(); + let session = ConversationId::from_string("019a7073-88e5-7461-93a0-adf67192b17b") + .expect("valid session id"); + let earliest_ms = logs.first().map(|e| e.timestamp_ms); + let latest_ms = logs.last().map(|e| e.timestamp_ms); + let returned = logs.len(); + let total = 21; // from exp4-real-run1 + let more = true; + + let mut pages = Vec::new(); + for max_lines in 1..=3 { + let rendered = render_logs_as_text_with_max_lines( + session, + &logs, + earliest_ms, + latest_ms, + returned, + total, + more, + max_lines, + PageDirection::Backward, + ); + pages.push(format!("lines={max_lines}\n{rendered}")); + } + + let snapshot = pages.join("\n---\n"); + + assert_snapshot!( + snapshot, + @r###"lines=1 +Session 019a7073-88e5-7461-93a0-adf67192b17b • status=waiting_on_tool • older_logs=true • at_latest=true +2025-11-11T01:06:53.628Z 🛠 exec bash -lc sleep 60 · cwd=/Users/friel/code/codex · running (0.0s) +--- +lines=2 +Session 019a7073-88e5-7461-93a0-adf67192b17b • status=waiting_on_tool • older_logs=true • at_latest=true +2025-11-11T01:06:53.442Z Reasoning summary: **Evaluating safe shell command execution** +2025-11-11T01:06:53.628Z 🛠 exec bash -lc sleep 60 · cwd=/Users/friel/code/codex · running (0.0s) +--- +lines=3 +Session 019a7073-88e5-7461-93a0-adf67192b17b • status=waiting_on_tool • older_logs=true • at_latest=true +2025-11-11T01:06:53.424Z Thinking: ** (1 delta) +2025-11-11T01:06:53.442Z Reasoning summary: **Evaluating safe shell command execution** +2025-11-11T01:06:53.628Z 🛠 exec bash -lc sleep 60 · cwd=/Users/friel/code/codex · running (0.0s)"### + ); +} + +#[test] +fn subagent_logs_snapshot_baseline() { + // Grounded in exp1-real-run1 first subagent_logs response (t=0). + let events_json = json!([ + { + "timestamp_ms": 1762823311742i64, + "event": { "id": "0", "msg": { "type": "agent_message", "message": "Hello world" } } + }, + { + "timestamp_ms": 1762823311766i64, + "event": { + "id": "0", + "msg": { + "type": "token_count", + "info": { + "total_token_usage": { + "input_tokens": 11073, + "cached_input_tokens": 11008, + "output_tokens": 8, + "reasoning_output_tokens": 0, + "total_tokens": 11081 + }, + "last_token_usage": { + "input_tokens": 11073, + "cached_input_tokens": 11008, + "output_tokens": 8, + "reasoning_output_tokens": 0, + "total_tokens": 11081 + }, + "model_context_window": 258400 + }, + "rate_limits": { "primary": null, "secondary": null } + } + } + }, + { + "timestamp_ms": 1762823311766i64, + "event": { + "id": "0", + "msg": { + "type": "raw_response_item", + "item": { + "type": "reasoning", + "summary": [ { "type": "summary_text", "text": "**Identifying sandbox requirements**" } ], + "content": null, + "encrypted_content": "[encrypted]" + } + } + } + }, + { + "timestamp_ms": 1762823311766i64, + "event": { + "id": "0", + "msg": { + "type": "raw_response_item", + "item": { + "type": "message", + "role": "assistant", + "content": [ { "type": "output_text", "text": "Hello world" } ] + } + } + } + }, + { + "timestamp_ms": 1762823311766i64, + "event": { + "id": "0", + "msg": { "type": "task_complete", "last_agent_message": "Hello world" } + } + } + ]); + + let logs: Vec = + serde_json::from_value(events_json).expect("valid baseline logs JSON"); + let session = ConversationId::from_string("019a7075-0760-79c2-8dd1-985772995ecf") + .expect("valid session id"); + let earliest_ms = logs.first().map(|e| e.timestamp_ms); + let latest_ms = logs.last().map(|e| e.timestamp_ms); + let returned = logs.len(); + let total = logs.len(); + let more = false; + + let rendered = render_logs_as_text( + session, + &logs, + earliest_ms, + latest_ms, + returned, + total, + more, + ); + + assert_snapshot!( + rendered, + @r###"Session 019a7075-0760-79c2-8dd1-985772995ecf • status=idle • older_logs=false • at_latest=true +2025-11-11T01:08:31.766Z Assistant: Hello world +2025-11-11T01:08:31.766Z Thinking: **Identifying sandbox requirements** +2025-11-11T01:08:31.766Z Task complete"### + ); +} + +#[test] +fn subagent_logs_snapshot_exec_sleep_command() { + // Grounded in exp4-real-run1 first subagent_logs response (t=0). + let logs = exec_sleep_logs(); + let session = ConversationId::from_string("019a7073-88e5-7461-93a0-adf67192b17b") + .expect("valid session id"); + let earliest_ms = logs.first().map(|e| e.timestamp_ms); + let latest_ms = logs.last().map(|e| e.timestamp_ms); + let returned = logs.len(); + let total = logs.len(); + let more = false; + + let rendered = render_logs_as_text( + session, + &logs, + earliest_ms, + latest_ms, + returned, + total, + more, + ); + + assert_snapshot!( + rendered, + @r###"Session 019a7073-88e5-7461-93a0-adf67192b17b • status=waiting_on_tool • older_logs=false • at_latest=true +2025-11-11T01:06:53.424Z Thinking: ** (1 delta) +2025-11-11T01:06:53.442Z Reasoning summary: **Evaluating safe shell command execution** +2025-11-11T01:06:53.628Z 🛠 exec bash -lc sleep 60 · cwd=/Users/friel/code/codex · running (0.0s)"### + ); +} + +#[test] +fn subagent_logs_snapshot_streaming_deltas() { + // Grounded in exp5-real-run1 agent_message_content_delta stream (t≈?s). + let events_json = json!([ + { + "timestamp_ms": 1762836527094i64, + "event": { "id": "0", "msg": { "type": "agent_message_content_delta", "thread_id": "019a713e-6ce6-7f82-b1e7-359628267934", "turn_id": "0", "item_id": "msg_0c5117240874292f016912c020d658819cb71e8bad4676a7c0", "delta": " is" } } + }, + { + "timestamp_ms": 1762836527105i64, + "event": { "id": "0", "msg": { "type": "agent_message_content_delta", "thread_id": "019a713e-6ce6-7f82-b1e7-359628267934", "turn_id": "0", "item_id": "msg_0c5117240874292f016912c020d658819cb71e8bad4676a7c0", "delta": " composing" } } + }, + { + "timestamp_ms": 1762836527121i64, + "event": { "id": "0", "msg": { "type": "agent_message_content_delta", "thread_id": "019a713e-6ce6-7f82-b1e7-359628267934", "turn_id": "0", "item_id": "msg_0c5117240874292f016912c020d658819cb71e8bad4676a7c0", "delta": " a" } } + }, + { + "timestamp_ms": 1762836527137i64, + "event": { "id": "0", "msg": { "type": "agent_message_content_delta", "thread_id": "019a713e-6ce6-7f82-b1e7-359628267934", "turn_id": "0", "item_id": "msg_0c5117240874292f016912c020d658819cb71e8bad4676a7c0", "delta": " longer" } } + }, + { + "timestamp_ms": 1762836527148i64, + "event": { "id": "0", "msg": { "type": "agent_message_content_delta", "thread_id": "019a713e-6ce6-7f82-b1e7-359628267934", "turn_id": "0", "item_id": "msg_0c5117240874292f016912c020d658819cb71e8bad4676a7c0", "delta": " answer" } } + } + ]); + let logs: Vec = + serde_json::from_value(events_json).expect("valid streaming_deltas JSON"); + let session = ConversationId::from_string("019a713e-6ce4-73e0-bf9b-e070890e3790") + .expect("valid session id"); + let earliest_ms = logs.first().map(|e| e.timestamp_ms); + let latest_ms = logs.last().map(|e| e.timestamp_ms); + let returned = logs.len(); + let total = logs.len(); + let more = false; + + let rendered = render_logs_as_text( + session, + &logs, + earliest_ms, + latest_ms, + returned, + total, + more, + ); + + assert_snapshot!( + rendered, + @r###"Session 019a713e-6ce4-73e0-bf9b-e070890e3790 • status=working • older_logs=false • at_latest=true + 2025-11-11T04:48:47.148Z Assistant (typing): is composing a longer answer (5 chunks)"### + ); +} + +#[test] +fn subagent_logs_snapshot_reasoning_stream() { + // Synthetic example of mid-reasoning without a summary yet. + let events_json = json!([ + { + "timestamp_ms": 1_000i64, + "event": { + "id": "0", + "msg": { + "type": "reasoning_content_delta", + "thread_id": "thread-1", + "turn_id": "0", + "item_id": "rs_test", + "delta": " thinking" + } + } + }, + { + "timestamp_ms": 1_050i64, + "event": { + "id": "0", + "msg": { + "type": "reasoning_content_delta", + "thread_id": "thread-1", + "turn_id": "0", + "item_id": "rs_test", + "delta": " about" + } + } + }, + { + "timestamp_ms": 1_100i64, + "event": { + "id": "0", + "msg": { + "type": "reasoning_content_delta", + "thread_id": "thread-1", + "turn_id": "0", + "item_id": "rs_test", + "delta": " streaming state" + } + } + } + ]); + let logs: Vec = + serde_json::from_value(events_json).expect("valid reasoning_stream JSON"); + let session = ConversationId::from_string("019a713e-eeee-73e0-bf9b-e070890e3790") + .expect("valid session id"); + let earliest_ms = logs.first().map(|e| e.timestamp_ms); + let latest_ms = logs.last().map(|e| e.timestamp_ms); + let returned = logs.len(); + let total = logs.len(); + let more = false; + + let rendered = render_logs_as_text( + session, + &logs, + earliest_ms, + latest_ms, + returned, + total, + more, + ); + + assert_snapshot!( + rendered, + @r###"Session 019a713e-eeee-73e0-bf9b-e070890e3790 • status=working • older_logs=false • at_latest=true + 1970-01-01T00:00:01.100Z Thinking: thinking about streaming state (3 deltas)"### + ); +} + +#[test] +fn subagent_logs_snapshot_no_older_history() { + // Minimal case: single assistant message, no older history, at latest. + let events_json = json!([ + { + "timestamp_ms": 1_000i64, + "event": { + "id": "0", + "msg": { "type": "agent_message", "message": "only event" } + } + } + ]); + let logs: Vec = serde_json::from_value(events_json).expect("valid single-event JSON"); + let session = ConversationId::from_string("019a9999-aaaa-bbbb-cccc-ddddeeeeffff") + .expect("valid session id"); + let earliest_ms = logs.first().map(|e| e.timestamp_ms); + let latest_ms = logs.last().map(|e| e.timestamp_ms); + let returned = logs.len(); + let total = logs.len(); + let more = false; + + let rendered = render_logs_as_text( + session, + &logs, + earliest_ms, + latest_ms, + returned, + total, + more, + ); + + assert_snapshot!( + rendered, + @r###"Session 019a9999-aaaa-bbbb-cccc-ddddeeeeffff • status=idle • older_logs=false • at_latest=true + 1970-01-01T00:00:01.000Z Assistant: only event"### + ); +} + +// Note: payload-shape and paging semantics (since_ms/before_ms/limit/max_bytes) +// are covered in focused unit tests in core/src/tools/handlers/subagent.rs. diff --git a/codex-rs/core/tests/suite/mod.rs b/codex-rs/core/tests/suite/mod.rs index b877663614..fc15aed412 100644 --- a/codex-rs/core/tests/suite/mod.rs +++ b/codex-rs/core/tests/suite/mod.rs @@ -49,6 +49,7 @@ mod seatbelt; mod shell_serialization; mod stream_error_allows_next_turn; mod stream_no_completed; +mod subagent_exec_events; mod text_encoding_fix; mod tool_harness; mod tool_parallelism; diff --git a/codex-rs/core/tests/suite/subagent_exec_events.rs b/codex-rs/core/tests/suite/subagent_exec_events.rs new file mode 100644 index 0000000000..2edcbe212a --- /dev/null +++ b/codex-rs/core/tests/suite/subagent_exec_events.rs @@ -0,0 +1,110 @@ +#![cfg(not(target_os = "windows"))] +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use anyhow::Result; +use codex_core::protocol::EventMsg; +use codex_core::protocol::ExecCommandBeginEvent; +use codex_core::protocol::ExecCommandEndEvent; +use codex_core::protocol::Op; +use codex_core::protocol::SandboxPolicy; +use codex_protocol::config_types::ReasoningSummary; +use codex_protocol::user_input::UserInput; +use core_test_support::responses::ev_assistant_message; +use core_test_support::responses::ev_completed; +use core_test_support::responses::ev_function_call; +use core_test_support::responses::ev_response_created; +use core_test_support::responses::sse; +use core_test_support::responses::start_mock_server; +use core_test_support::test_codex::test_codex; +use core_test_support::wait_for_event_with_timeout; +use serde_json::json; +use tokio::time::Duration; + +fn is_exec_begin(ev: &EventMsg) -> Option { + if let EventMsg::ExecCommandBegin(ev) = ev { + Some(ev.clone()) + } else { + None + } +} + +fn is_exec_end(ev: &EventMsg) -> Option { + if let EventMsg::ExecCommandEnd(ev) = ev { + Some(ev.clone()) + } else { + None + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[ignore = "relies on streaming timing; kept for manual verification"] +async fn root_subagent_tool_emits_exec_events() -> Result<()> { + let server = start_mock_server().await; + let mut builder = test_codex(); + let test = builder.build(&server).await?; + + let call_id = "subagent-call"; + let args = json!({}); + + // First completion triggers the subagent tool call. + core_test_support::responses::mount_sse_once( + &server, + sse(vec![ + ev_response_created("resp-1"), + ev_function_call(call_id, "subagent_list", &args.to_string()), + ev_completed("resp-1"), + ]), + ) + .await; + // Second completion finishes the turn. + core_test_support::responses::mount_sse_once( + &server, + sse(vec![ + ev_response_created("resp-2"), + ev_assistant_message("msg-1", "done"), + ev_completed("resp-2"), + ]), + ) + .await; + + test.codex + .submit(Op::UserTurn { + items: vec![UserInput::Text { + text: "spawn one please".to_string(), + }], + final_output_json_schema: None, + cwd: test.cwd.path().to_path_buf(), + approval_policy: codex_core::protocol::AskForApproval::Never, + sandbox_policy: SandboxPolicy::DangerFullAccess, + model: test.session_configured.model.clone(), + effort: None, + summary: ReasoningSummary::Auto, + }) + .await?; + + let mut begin: Option = None; + let mut end: Option = None; + for _ in 0..40 { + let ev = wait_for_event_with_timeout(&test.codex, |_| true, Duration::from_secs(20)).await; + if begin.is_none() { + begin = is_exec_begin(&ev); + } + if end.is_none() { + end = is_exec_end(&ev); + } + if matches!(ev, EventMsg::TaskComplete(_)) && begin.is_some() && end.is_some() { + break; + } + } + + let begin = begin.expect("exec begin"); + assert_eq!( + begin.command.first().map(String::as_str), + Some("subagent_list") + ); + let end = end.expect("exec end"); + assert_eq!(end.call_id, begin.call_id); + assert_eq!(end.exit_code, 0); + + Ok(()) +} diff --git a/codex-rs/docs/protocol_v1.md b/codex-rs/docs/protocol_v1.md index f6405c9bc3..6fe13efca6 100644 --- a/codex-rs/docs/protocol_v1.md +++ b/codex-rs/docs/protocol_v1.md @@ -42,6 +42,10 @@ These are entities exit on the codex backend. The intent of this section is to e The term "UI" is used to refer to the application driving `Codex`. This may be the CLI / TUI chat-like interface that users operate, or it may be a GUI interface like a VSCode extension. The UI is external to `Codex`, as `Codex` is intended to be operated by arbitrary UI implementations. +### Agent identifiers + +Every participant in a session (the root UI thread plus each spawned/forked child) is assigned a monotonically increasing numeric `AgentId`. Agent `0` is always the root thread. Subagents inherit their parent's `AgentId` as `parent_agent_id` so UIs can correlate trees even when conversations are forked or exported. These IDs are surfaced in `SubagentSummary` payloads and in a dedicated inbox event described below. + When a `Turn` completes, the `response_id` from the `Model`'s final `response.completed` message is stored in the `Session` state to resume the thread given the next `Op::UserInput`. The `response_id` is also returned in the `EventMsg::TurnComplete` to the UI, which can be used to fork the thread from an earlier point by providing it in the `Op::UserInput`. Since only 1 `Task` can be run at a time, for parallel tasks it is recommended that a single `Codex` be run for each thread of work. @@ -75,6 +79,11 @@ For complete documentation of the `Op` and `EventMsg` variants, refer to [protoc - `EventMsg::Error` – A task stopped with an error - `EventMsg::Warning` – A non-fatal warning that the client should surface to the user - `EventMsg::TurnComplete` – Contains a `response_id` bookmark for last `response_id` executed by the task. This can be used to continue the task at a later point in time, perhaps with additional user input. +- `EventMsg::SubagentLifecycle` – Emits `SubagentSummary` payloads (now including `agent_id`, `parent_agent_id`, and pending inbox counts) whenever a child session is created, updates status/reasoning headers, or is removed. + These lifecycle events now persist in rollout files so `codex resume` can restore prior subagent state (attachments on spawn/fork and detach on cancel/prune). +- `EventMsg::AgentInbox` – Notifies the UI when a subagent’s inbox depth changes, e.g., after the parent sends an interrupt. Contains the target `agent_id`, `session_id`, and the counts of pending regular vs interrupt messages so UIs can render badges without polling. + +Subagent tool reminders: `subagent_await` accepts an optional `timeout_s` capped at 1,800 s (30 minutes). Omit it or pass 0 to use the 30-minute default; prefer at least 300 s and use backoff (30s → 60s → 120s) so you can check on children, log progress, or deliver interrupts instead of parking for the full cap. The `response_id` returned from each task matches the OpenAI `response_id` stored in the API's `/responses` endpoint. It can be stored and used in future `Sessions` to resume threads of work. diff --git a/codex-rs/exec/src/cli.rs b/codex-rs/exec/src/cli.rs index 6866bc0ff7..49bfec89ff 100644 --- a/codex-rs/exec/src/cli.rs +++ b/codex-rs/exec/src/cli.rs @@ -91,6 +91,9 @@ pub struct Cli { pub enum Command { /// Resume a previous session by id or pick the most recent with --last. Resume(ResumeArgs), + + /// Fork an existing session into a new branch and immediately run a prompt. + Fork(ForkArgs), } #[derive(Parser, Debug)] @@ -109,6 +112,17 @@ pub struct ResumeArgs { pub prompt: Option, } +#[derive(Parser, Debug)] +pub struct ForkArgs { + /// Session id (UUID) to fork into a new branch. + #[arg(value_name = "SESSION_ID")] + pub session_id: String, + + /// Prompt to send after forking. If `-` is used, read from stdin. + #[arg(value_name = "PROMPT", value_hint = clap::ValueHint::Other)] + pub prompt: Option, +} + #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, ValueEnum)] #[value(rename_all = "kebab-case")] pub enum Color { diff --git a/codex-rs/exec/src/event_processor_with_human_output.rs b/codex-rs/exec/src/event_processor_with_human_output.rs index f0bb707207..14680f555c 100644 --- a/codex-rs/exec/src/event_processor_with_human_output.rs +++ b/codex-rs/exec/src/event_processor_with_human_output.rs @@ -1,6 +1,7 @@ use codex_common::elapsed::format_duration; use codex_common::elapsed::format_elapsed; use codex_core::config::Config; +use codex_core::protocol::AgentInboxEvent; use codex_core::protocol::AgentMessageEvent; use codex_core::protocol::AgentReasoningRawContentEvent; use codex_core::protocol::BackgroundEventEvent; @@ -18,11 +19,14 @@ use codex_core::protocol::PatchApplyBeginEvent; use codex_core::protocol::PatchApplyEndEvent; use codex_core::protocol::SessionConfiguredEvent; use codex_core::protocol::StreamErrorEvent; +use codex_core::protocol::SubagentLifecycleEvent; use codex_core::protocol::TaskCompleteEvent; use codex_core::protocol::TurnAbortReason; use codex_core::protocol::TurnDiffEvent; use codex_core::protocol::WarningEvent; use codex_core::protocol::WebSearchEndEvent; +use codex_protocol::AgentId; +use codex_protocol::ConversationId; use codex_protocol::num_format::format_with_separators; use owo_colors::OwoColorize; use owo_colors::Style; @@ -43,6 +47,7 @@ use codex_protocol::plan_tool::UpdatePlanArgs; const MAX_OUTPUT_LINES_FOR_EXEC_TOOL_CALL: usize = 20; pub(crate) struct EventProcessorWithHumanOutput { call_id_to_patch: HashMap, + subagents: HashMap, // To ensure that --color=never is respected, ANSI escapes _must_ be added // using .style() with one of these fields. If you need a new style, add a @@ -65,6 +70,11 @@ pub(crate) struct EventProcessorWithHumanOutput { final_message: Option, } +#[derive(Clone, Debug)] +struct SubagentCliInfo { + label: Option, +} + impl EventProcessorWithHumanOutput { pub(crate) fn create_with_ansi( with_ansi: bool, @@ -76,6 +86,7 @@ impl EventProcessorWithHumanOutput { if with_ansi { Self { call_id_to_patch, + subagents: HashMap::new(), bold: Style::new().bold(), italic: Style::new().italic(), dimmed: Style::new().dimmed(), @@ -93,6 +104,7 @@ impl EventProcessorWithHumanOutput { } else { Self { call_id_to_patch, + subagents: HashMap::new(), bold: Style::new(), italic: Style::new(), dimmed: Style::new(), @@ -546,6 +558,8 @@ impl EventProcessor for EventProcessorWithHumanOutput { ts_msg!(self, "task aborted: review ended"); } }, + EventMsg::SubagentLifecycle(ev) => self.log_subagent_lifecycle(ev), + EventMsg::AgentInbox(ev) => self.log_agent_inbox(ev), EventMsg::ShutdownComplete => return CodexStatus::Shutdown, EventMsg::WebSearchBegin(_) | EventMsg::ExecApprovalRequest(_) @@ -595,6 +609,106 @@ impl EventProcessor for EventProcessorWithHumanOutput { } } } +impl EventProcessorWithHumanOutput { + fn log_subagent_lifecycle(&mut self, event: SubagentLifecycleEvent) { + match event { + SubagentLifecycleEvent::Created(created) => { + let name = self.render_subagent_name( + &created.subagent.session_id, + created.subagent.agent_id, + created.subagent.label.as_deref(), + ); + self.subagents.insert( + created.subagent.session_id, + SubagentCliInfo { + label: created.subagent.label.clone(), + }, + ); + ts_msg!( + self, + "[#{}] {} created via {:?}", + created.subagent.agent_id, + name.style(self.cyan), + created.subagent.origin + ); + } + SubagentLifecycleEvent::Status(status) => { + let name = self.render_subagent_name(&status.session_id, status.agent_id, None); + ts_msg!( + self, + "[#{}] {} status → {:?}", + status.agent_id, + name.style(self.cyan), + status.status + ); + } + SubagentLifecycleEvent::ReasoningHeader(reasoning) => { + let name = + self.render_subagent_name(&reasoning.session_id, reasoning.agent_id, None); + ts_msg!( + self, + "[#{}] {} header: {}", + reasoning.agent_id, + name.style(self.cyan), + reasoning.reasoning_header.style(self.italic) + ); + } + SubagentLifecycleEvent::Deleted(removed) => { + let name = self.render_subagent_name(&removed.session_id, removed.agent_id, None); + self.subagents.remove(&removed.session_id); + ts_msg!( + self, + "[#{}] {} removed", + removed.agent_id, + name.style(self.cyan) + ); + } + } + } + + fn log_agent_inbox(&mut self, event: AgentInboxEvent) { + let name = self.render_subagent_name(&event.session_id, event.agent_id, None); + ts_msg!( + self, + "[#{}] {} inbox: {} msg{}, {} interrupt{}", + event.agent_id, + name.style(self.cyan), + event.pending_messages, + if event.pending_messages == 1 { "" } else { "s" }, + event.pending_interrupts, + if event.pending_interrupts == 1 { + "" + } else { + "s" + } + ); + } + + fn render_subagent_name( + &self, + session_id: &ConversationId, + agent_id: AgentId, + explicit: Option<&str>, + ) -> String { + if let Some(name) = explicit + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(std::string::ToString::to_string) + .or_else(|| { + self.subagents + .get(session_id) + .and_then(|info| info.label.as_deref()) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(std::string::ToString::to_string) + }) + { + return name; + } + let short = session_id.to_string().chars().take(8).collect::(); + format!("subagent #{agent_id} ({short})") + } +} fn escape_command(command: &[String]) -> String { try_join(command.iter().map(String::as_str)).unwrap_or_else(|_| command.join(" ")) diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index 830bb841cd..11719e5ff1 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -10,6 +10,8 @@ mod event_processor_with_human_output; pub mod event_processor_with_jsonl_output; pub mod exec_events; +use anyhow::Context; +use anyhow::anyhow; pub use cli::Cli; use codex_common::oss::ensure_oss_provider_ready; use codex_common::oss::get_default_model_for_oss_provider; @@ -18,6 +20,7 @@ use codex_core::ConversationManager; use codex_core::LMSTUDIO_OSS_PROVIDER_ID; use codex_core::NewConversation; use codex_core::OLLAMA_OSS_PROVIDER_ID; +use codex_core::RolloutRecorder; use codex_core::auth::enforce_login_restrictions; use codex_core::config::Config; use codex_core::config::ConfigOverrides; @@ -31,6 +34,7 @@ use codex_core::protocol::EventMsg; use codex_core::protocol::Op; use codex_core::protocol::SessionSource; use codex_protocol::config_types::SandboxMode; +use codex_protocol::protocol::InitialHistory; use codex_protocol::user_input::UserInput; use event_processor_with_human_output::EventProcessorWithHumanOutput; use event_processor_with_jsonl_output::EventProcessorWithJsonOutput; @@ -39,6 +43,7 @@ use serde_json::Value; use std::io::IsTerminal; use std::io::Read; use std::path::PathBuf; +use std::sync::Arc; use supports_color::Stream; use tracing::debug; use tracing::error; @@ -97,6 +102,7 @@ pub async fn run_main(cli: Cli, codex_linux_sandbox_exe: Option) -> any }); resume_prompt.or(prompt) } + Some(ExecCommand::Fork(args)) => args.prompt.clone().or(prompt), None => prompt, }; @@ -240,6 +246,10 @@ pub async fn run_main(cli: Cli, codex_linux_sandbox_exe: Option) -> any base_instructions: None, developer_instructions: None, compact_prompt: None, + max_active_subagents: None, + root_agent_uses_user_messages: None, + subagent_root_inbox_autosubmit: None, + subagent_inbox_inject_before_tools: None, include_apply_patch_tool: None, show_raw_agent_reasoning: oss.then_some(true), tools_web_search_request: None, @@ -323,27 +333,39 @@ pub async fn run_main(cli: Cli, codex_linux_sandbox_exe: Option) -> any ); let conversation_manager = ConversationManager::new(auth_manager.clone(), SessionSource::Exec); - // Handle resume subcommand by resolving a rollout path and using explicit resume API. + // Handle resume/fork subcommands by resolving a rollout path and using the explicit resume API. let NewConversation { conversation_id: _, conversation, session_configured, - } = if let Some(ExecCommand::Resume(args)) = command { - let resume_path = resolve_resume_path(&config, &args).await?; - - if let Some(path) = resume_path { - conversation_manager - .resume_conversation_from_rollout(config.clone(), path, auth_manager.clone()) - .await? - } else { + } = match &command { + Some(ExecCommand::Resume(args)) => { + let resume_path = resolve_resume_path(&config, args).await?; + if let Some(path) = resume_path { + conversation_manager + .resume_conversation_from_rollout(config.clone(), path, auth_manager.clone()) + .await? + } else { + conversation_manager + .new_conversation(config.clone()) + .await? + } + } + Some(ExecCommand::Fork(args)) => { + let path = resolve_fork_path(&config, &args.session_id).await?; + fork_conversation_from_rollout( + &conversation_manager, + &config, + auth_manager.clone(), + path, + ) + .await? + } + None => { conversation_manager .new_conversation(config.clone()) .await? } - } else { - conversation_manager - .new_conversation(config.clone()) - .await? }; // Print the effective configuration and prompt so users can see what Codex // is using. @@ -467,6 +489,32 @@ async fn resolve_resume_path( } } +async fn resolve_fork_path(config: &Config, session_id: &str) -> anyhow::Result { + find_conversation_path_by_id_str(&config.codex_home, session_id) + .await? + .ok_or_else(|| anyhow!("No session with id {session_id} found")) +} + +async fn fork_conversation_from_rollout( + conversation_manager: &ConversationManager, + config: &Config, + auth_manager: Arc, + path: PathBuf, +) -> anyhow::Result { + let history = RolloutRecorder::get_rollout_history(&path) + .await + .context("failed to read session history for fork")?; + let fork_history = match history { + InitialHistory::New => InitialHistory::New, + InitialHistory::Resumed(resumed) => InitialHistory::Forked(resumed.history), + InitialHistory::Forked(items) => InitialHistory::Forked(items), + }; + conversation_manager + .resume_conversation_with_history(config.clone(), fork_history, auth_manager) + .await + .map_err(anyhow::Error::from) +} + fn load_output_schema(path: Option) -> Option { let path = path?; diff --git a/codex-rs/exec/tests/event_processor_with_json_output.rs b/codex-rs/exec/tests/event_processor_with_json_output.rs index 06f99b96b1..4e6b208126 100644 --- a/codex-rs/exec/tests/event_processor_with_json_output.rs +++ b/codex-rs/exec/tests/event_processor_with_json_output.rs @@ -642,6 +642,7 @@ fn exec_command_end_success_produces_completed_command_item() { cwd: cwd.clone(), parsed_cmd: parsed_cmd.clone(), source: ExecCommandSource::Agent, + is_user_shell_command: false, interaction_input: None, }), ); @@ -714,6 +715,7 @@ fn exec_command_end_failure_produces_failed_command_item() { cwd: cwd.clone(), parsed_cmd: parsed_cmd.clone(), source: ExecCommandSource::Agent, + is_user_shell_command: false, interaction_input: None, }), ); diff --git a/codex-rs/exec/tests/suite/resume.rs b/codex-rs/exec/tests/suite/resume.rs index e37b38606a..1f276f663c 100644 --- a/codex-rs/exec/tests/suite/resume.rs +++ b/codex-rs/exec/tests/suite/resume.rs @@ -309,3 +309,70 @@ fn exec_resume_preserves_cli_configuration_overrides() -> anyhow::Result<()> { assert!(content.contains(&marker2)); Ok(()) } + +#[test] +fn exec_fork_creates_new_session() -> anyhow::Result<()> { + let test = test_codex_exec(); + let fixture = + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/cli_responses_fixture.sse"); + + // Seed conversation. + let marker = format!("fork-source-{}", Uuid::new_v4()); + let prompt = format!("echo {marker}"); + + test.cmd() + .env("CODEX_RS_SSE_FIXTURE", &fixture) + .env("OPENAI_BASE_URL", "http://unused.local") + .arg("--skip-git-repo-check") + .arg("-C") + .arg(env!("CARGO_MANIFEST_DIR")) + .arg(&prompt) + .assert() + .success(); + + let sessions_dir = test.home_path().join("sessions"); + let source_path = find_session_file_containing_marker(&sessions_dir, &marker) + .expect("no session file found after source run"); + let source_id = extract_conversation_id(&source_path); + assert!( + !source_id.is_empty(), + "missing conversation id in source session" + ); + + // Fork with a new prompt. + let marker2 = format!("fork-branch-{}", Uuid::new_v4()); + let prompt2 = format!("echo {marker2}"); + + test.cmd() + .env("CODEX_RS_SSE_FIXTURE", &fixture) + .env("OPENAI_BASE_URL", "http://unused.local") + .arg("--skip-git-repo-check") + .arg("-C") + .arg(env!("CARGO_MANIFEST_DIR")) + .arg("fork") + .arg(&source_id) + .arg(&prompt2) + .assert() + .success(); + + let forked_path = find_session_file_containing_marker(&sessions_dir, &marker2) + .expect("no forked session file containing new marker"); + assert_ne!( + forked_path, source_path, + "fork should produce a new session file" + ); + + let source_content = std::fs::read_to_string(&source_path)?; + assert!( + !source_content.contains(&marker2), + "source session must remain unchanged" + ); + + let forked_content = std::fs::read_to_string(&forked_path)?; + assert!( + forked_content.contains(&marker) && forked_content.contains(&marker2), + "forked session should contain both original and new prompts" + ); + + Ok(()) +} diff --git a/codex-rs/image.png b/codex-rs/image.png new file mode 100644 index 0000000000..785c3037d7 Binary files /dev/null and b/codex-rs/image.png differ diff --git a/codex-rs/justfile b/codex-rs/justfile index b1b9d7337b..6d351c17a2 100644 --- a/codex-rs/justfile +++ b/codex-rs/justfile @@ -28,7 +28,7 @@ app-server-test-client *args: # format code fmt: - cargo fmt -- --config imports_granularity=Item + cargo +nightly fmt -- --config imports_granularity=Item fix *args: cargo clippy --fix --all-features --tests --allow-dirty "$@" diff --git a/codex-rs/mcp-server/src/codex_tool_config.rs b/codex-rs/mcp-server/src/codex_tool_config.rs index 4e61bde02b..0587702f60 100644 --- a/codex-rs/mcp-server/src/codex_tool_config.rs +++ b/codex-rs/mcp-server/src/codex_tool_config.rs @@ -166,6 +166,10 @@ impl CodexToolCallParam { base_instructions, developer_instructions, compact_prompt, + max_active_subagents: None, + root_agent_uses_user_messages: None, + subagent_root_inbox_autosubmit: None, + subagent_inbox_inject_before_tools: None, include_apply_patch_tool: None, show_raw_agent_reasoning: None, tools_web_search_request: None, diff --git a/codex-rs/mcp-server/src/codex_tool_runner.rs b/codex-rs/mcp-server/src/codex_tool_runner.rs index 8dccb51250..a01d61eb55 100644 --- a/codex-rs/mcp-server/src/codex_tool_runner.rs +++ b/codex-rs/mcp-server/src/codex_tool_runner.rs @@ -302,7 +302,9 @@ async fn run_codex_tool_session_inner( | EventMsg::UndoStarted(_) | EventMsg::UndoCompleted(_) | EventMsg::ExitedReviewMode(_) - | EventMsg::DeprecationNotice(_) => { + | EventMsg::DeprecationNotice(_) + | EventMsg::SubagentLifecycle(_) + | EventMsg::AgentInbox(_) => { // For now, we do not do anything extra for these // events. Note that // send(codex_event_to_notification(&event)) above has diff --git a/codex-rs/protocol/src/lib.rs b/codex-rs/protocol/src/lib.rs index 08ea753347..65e36a894e 100644 --- a/codex-rs/protocol/src/lib.rs +++ b/codex-rs/protocol/src/lib.rs @@ -1,6 +1,8 @@ pub mod account; mod conversation_id; pub use conversation_id::ConversationId; +/// Numeric identifier for agents/subagents (agent 0 is always the root UI thread). +pub type AgentId = u64; pub mod approvals; pub mod config_types; pub mod custom_prompts; diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index e0c2e4df3f..335543d537 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -10,6 +10,7 @@ use std::path::PathBuf; use std::str::FromStr; use std::time::Duration; +use crate::AgentId; use crate::ConversationId; use crate::config_types::ReasoningEffort as ReasoningEffortConfig; use crate::config_types::ReasoningSummary as ReasoningSummaryConfig; @@ -470,6 +471,12 @@ pub enum EventMsg { /// Raw chain-of-thought from agent. AgentReasoningRawContent(AgentReasoningRawContentEvent), + /// Lifecycle update for a subagent (spawned/forked/resumed child session). + SubagentLifecycle(SubagentLifecycleEvent), + + /// Notification that a subagent's inbox depth changed (e.g., parent sent an interrupt). + AgentInbox(AgentInboxEvent), + /// Agent reasoning content delta event from agent. AgentReasoningRawContentDelta(AgentReasoningRawContentDeltaEvent), /// Signaled when the model begins a new reasoning summary section (e.g., a new titled block). @@ -969,6 +976,92 @@ pub struct AgentReasoningRawContentEvent { pub text: String, } +#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS, PartialEq, Eq, Copy)] +#[serde(rename_all = "snake_case")] +#[ts(export)] +pub enum SubagentLifecycleOrigin { + Spawn, + Fork, + SendMessage, +} + +#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS, PartialEq, Eq, Copy)] +#[serde(rename_all = "snake_case")] +#[ts(export)] +pub enum SubagentLifecycleStatus { + Queued, + Running, + Ready, + Idle, + Failed, + Canceled, +} + +#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] +#[ts(export)] +pub struct SubagentSummary { + pub agent_id: AgentId, + pub parent_agent_id: Option, + pub session_id: ConversationId, + pub parent_session_id: Option, + pub origin: SubagentLifecycleOrigin, + pub status: SubagentLifecycleStatus, + pub label: Option, + pub summary: Option, + pub reasoning_header: Option, + pub started_at_ms: i64, + pub pending_messages: usize, + pub pending_interrupts: usize, +} + +#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] +#[serde(tag = "event", rename_all = "snake_case")] +#[ts(export)] +pub enum SubagentLifecycleEvent { + Created(SubagentCreatedEvent), + Status(SubagentStatusEvent), + ReasoningHeader(SubagentReasoningHeaderEvent), + Deleted(SubagentRemovedEvent), +} + +#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] +#[ts(export)] +pub struct SubagentCreatedEvent { + pub subagent: SubagentSummary, +} + +#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] +#[ts(export)] +pub struct SubagentStatusEvent { + pub agent_id: AgentId, + pub session_id: ConversationId, + pub status: SubagentLifecycleStatus, +} + +#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] +#[ts(export)] +pub struct SubagentReasoningHeaderEvent { + pub agent_id: AgentId, + pub session_id: ConversationId, + pub reasoning_header: String, +} + +#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] +#[ts(export)] +pub struct SubagentRemovedEvent { + pub agent_id: AgentId, + pub session_id: ConversationId, +} + +#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] +#[ts(export)] +pub struct AgentInboxEvent { + pub agent_id: AgentId, + pub session_id: ConversationId, + pub pending_messages: usize, + pub pending_interrupts: usize, +} + #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] pub struct AgentReasoningRawContentDeltaEvent { pub delta: String, @@ -1294,6 +1387,9 @@ pub struct ExecCommandBeginEvent { /// Where the command originated. Defaults to Agent for backward compatibility. #[serde(default)] pub source: ExecCommandSource, + /// Whether the command was explicitly requested as a local user shell command. + #[serde(default)] + pub is_user_shell_command: bool, /// Raw input sent to a unified exec session (if this is an interaction event). #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index 5dbfb210b2..606ae18271 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -6,6 +6,7 @@ use crate::bottom_pane::queued_user_messages::QueuedUserMessages; use crate::render::renderable::FlexRenderable; use crate::render::renderable::Renderable; use crate::render::renderable::RenderableItem; +use crate::shimmer::shimmer_spans; use crate::tui::FrameRequester; use bottom_pane_view::BottomPaneView; use codex_file_search::FileMatch; @@ -13,6 +14,9 @@ use crossterm::event::KeyCode; use crossterm::event::KeyEvent; use ratatui::buffer::Buffer; use ratatui::layout::Rect; +use ratatui::style::Stylize; +use ratatui::text::Line; +use ratatui::text::Span; use std::time::Duration; mod approval_overlay; @@ -48,6 +52,7 @@ pub(crate) enum CancellationEvent { pub(crate) use chat_composer::ChatComposer; pub(crate) use chat_composer::InputResult; use codex_protocol::custom_prompts::CustomPrompt; +use codex_protocol::protocol::SubagentLifecycleStatus; use crate::status_indicator_widget::StatusIndicatorWidget; pub(crate) use list_selection_view::SelectionAction; @@ -75,6 +80,8 @@ pub(crate) struct BottomPane { status: Option, /// Queued user messages to show above the composer while a turn is running. queued_user_messages: QueuedUserMessages, + subagent_summaries: SubagentSummariesWidget, + subagent_count: usize, context_window_percent: Option, } @@ -115,6 +122,8 @@ impl BottomPane { ctrl_c_quit_hint: false, status: None, queued_user_messages: QueuedUserMessages::new(), + subagent_summaries: SubagentSummariesWidget::default(), + subagent_count: 0, esc_backtrack_hint: false, animations_enabled, context_window_percent: None, @@ -278,6 +287,16 @@ impl BottomPane { self.status.is_some() } + #[cfg(test)] + pub(crate) fn subagent_entries(&self) -> &[SubagentDisplayEntry] { + &self.subagent_summaries.entries + } + + #[cfg(test)] + pub(crate) fn subagent_count(&self) -> usize { + self.subagent_count + } + pub(crate) fn show_esc_backtrack_hint(&mut self) { self.esc_backtrack_hint = true; self.composer.set_esc_backtrack_hint(true); @@ -308,11 +327,12 @@ impl BottomPane { self.animations_enabled, )); } - if let Some(status) = self.status.as_mut() { - status.set_interrupt_hint_visible(true); - } - self.request_redraw(); } + if let Some(status) = self.status.as_mut() { + status.set_interrupt_hint_visible(true); + status.set_subagent_count(self.subagent_count); + } + self.request_redraw(); } else { // Hide the status indicator when a task completes, but keep other modal views. self.hide_status_indicator(); @@ -335,6 +355,9 @@ impl BottomPane { )); self.request_redraw(); } + if let Some(status) = self.status.as_mut() { + status.set_subagent_count(self.subagent_count); + } } pub(crate) fn set_interrupt_hint_visible(&mut self, visible: bool) { @@ -366,6 +389,23 @@ impl BottomPane { self.request_redraw(); } + pub(crate) fn update_subagent_summaries(&mut self, entries: Vec) { + if self.subagent_summaries.update(entries) { + self.request_redraw(); + } + } + + pub(crate) fn set_subagent_counts(&mut self, count: usize) { + if self.subagent_count == count { + return; + } + self.subagent_count = count; + if let Some(status) = self.status.as_mut() { + status.set_subagent_count(count); + } + self.request_redraw(); + } + /// Update custom prompts available for the slash popup. pub(crate) fn set_custom_prompts(&mut self, prompts: Vec) { self.composer.set_custom_prompts(prompts); @@ -495,6 +535,9 @@ impl BottomPane { let mut flex = FlexRenderable::new(); if let Some(status) = &self.status { flex.push(0, RenderableItem::Borrowed(status)); + if !self.subagent_summaries.is_empty() { + flex.push(0, RenderableItem::Borrowed(&self.subagent_summaries)); + } } flex.push(1, RenderableItem::Borrowed(&self.queued_user_messages)); if self.status.is_some() || !self.queued_user_messages.messages.is_empty() { @@ -520,6 +563,108 @@ impl Renderable for BottomPane { } } +#[derive(Default)] +struct SubagentSummariesWidget { + entries: Vec, +} + +impl SubagentSummariesWidget { + fn update(&mut self, entries: Vec) -> bool { + if self.entries == entries { + return false; + } + self.entries = entries; + true + } + + fn is_empty(&self) -> bool { + self.entries.is_empty() + } +} + +impl Renderable for SubagentSummariesWidget { + fn desired_height(&self, _width: u16) -> u16 { + self.entries.len().min(u16::MAX as usize) as u16 + } + + fn render(&self, area: Rect, buf: &mut Buffer) { + for (idx, entry) in self.entries.iter().enumerate() { + let y = area.y + idx as u16; + if y >= area.bottom() { + break; + } + let line_area = Rect::new(area.x, y, area.width, 1); + entry.render(line_area, buf); + } + } +} + +#[derive(Clone, PartialEq)] +pub(crate) enum SubagentDisplayEntryKind { + Summary, + Item, +} + +#[derive(Clone, PartialEq)] +pub(crate) struct SubagentDisplayEntry { + pub(crate) kind: SubagentDisplayEntryKind, + pub(crate) label: String, + pub(crate) detail: Option, + pub(crate) status: Option, +} + +impl SubagentDisplayEntry { + fn render(&self, area: Rect, buf: &mut Buffer) { + let line = match self.kind { + SubagentDisplayEntryKind::Summary => { + let mut spans: Vec = vec![" • ".dim(), self.label.clone().dim()]; + if let Some(detail) = &self.detail { + spans.push(" — ".dim()); + spans.push(detail.clone().dim()); + } + Line::from(spans) + } + SubagentDisplayEntryKind::Item => { + let mut spans: Vec = Vec::new(); + spans.push(" • ".dim()); + spans.push(self.label.clone().bold()); + if let Some(status) = self.status { + spans.push(" ".into()); + spans.push(status_to_span(status)); + } + if let Some(detail) = &self.detail { + spans.push(" — ".dim()); + let should_shimmer = + matches!(self.status, Some(SubagentLifecycleStatus::Running)); + if should_shimmer { + let shimmer = shimmer_spans(detail); + if shimmer.is_empty() { + spans.push(detail.clone().into()); + } else { + spans.extend(shimmer); + } + } else { + spans.push(detail.clone().into()); + } + } + Line::from(spans) + } + }; + line.render(area, buf); + } +} + +fn status_to_span(status: SubagentLifecycleStatus) -> Span<'static> { + match status { + SubagentLifecycleStatus::Queued => "queued".blue(), + SubagentLifecycleStatus::Running => "running".green(), + SubagentLifecycleStatus::Ready => "ready".cyan(), + SubagentLifecycleStatus::Idle => "idle".dim(), + SubagentLifecycleStatus::Failed => "failed".red(), + SubagentLifecycleStatus::Canceled => "canceled".magenta(), + } +} + #[cfg(test)] mod tests { use super::*; @@ -609,6 +754,75 @@ mod tests { ); } + #[test] + fn subagent_summary_height_clamped() { + let mut widget = SubagentSummariesWidget::default(); + let entries: Vec = (0..100_000) + .map(|i| SubagentDisplayEntry { + kind: SubagentDisplayEntryKind::Item, + label: format!("agent-{i}"), + detail: None, + status: None, + }) + .collect(); + widget.update(entries); + assert_eq!(widget.desired_height(80), u16::MAX); + } + + #[test] + fn subagent_shimmer_only_when_running() { + let mut entry = SubagentDisplayEntry { + kind: SubagentDisplayEntryKind::Item, + label: "agent".to_string(), + detail: Some("working".to_string()), + status: Some(SubagentLifecycleStatus::Ready), + }; + let area = Rect::new(0, 0, 40, 1); + let mut buf = Buffer::empty(area); + entry.render(area, &mut buf); + let line_ready = snapshot_buffer(&buf); + + entry.status = Some(SubagentLifecycleStatus::Running); + let mut buf_run = Buffer::empty(area); + entry.render(area, &mut buf_run); + let line_run = snapshot_buffer(&buf_run); + + assert!( + line_run.contains("working"), + "running state should still show detail text" + ); + assert!( + line_run != line_ready, + "running state should visually differ (shimmer) from non-running" + ); + } + + #[test] + fn subagent_count_persists_across_status_hide() { + let (tx_raw, _rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let mut pane = BottomPane::new(BottomPaneParams { + app_event_tx: tx, + frame_requester: FrameRequester::test_dummy(), + has_input_focus: true, + enhanced_keys_supported: false, + placeholder_text: "Ask Codex to do anything".to_string(), + disable_paste_burst: false, + }); + + pane.set_task_running(true); + pane.set_subagent_counts(3); + pane.hide_status_indicator(); + pane.ensure_status_indicator(); + + let area = Rect::new(0, 0, 60, 2); + let snapshot = render_snapshot(&pane, area); + assert!( + snapshot.contains("3 subagents"), + "subagent count should survive hide/show of status indicator" + ); + } + #[test] fn composer_shown_after_denied_while_task_running() { let (tx_raw, _rx) = unbounded_channel::(); diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index a371fa8cb8..5e5ca51c71 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -11,6 +11,7 @@ use codex_core::config::types::Notifications; use codex_core::git_info::current_branch_name; use codex_core::git_info::local_git_branches; use codex_core::project_doc::DEFAULT_PROJECT_DOC_FILENAME; +use codex_core::protocol::AgentInboxEvent; use codex_core::protocol::AgentMessageDeltaEvent; use codex_core::protocol::AgentMessageEvent; use codex_core::protocol::AgentReasoningDeltaEvent; @@ -40,6 +41,9 @@ use codex_core::protocol::PatchApplyBeginEvent; use codex_core::protocol::RateLimitSnapshot; use codex_core::protocol::ReviewRequest; use codex_core::protocol::StreamErrorEvent; +use codex_core::protocol::SubagentLifecycleEvent; +use codex_core::protocol::SubagentLifecycleStatus; +use codex_core::protocol::SubagentSummary; use codex_core::protocol::TaskCompleteEvent; use codex_core::protocol::TokenUsage; use codex_core::protocol::TokenUsageInfo; @@ -52,6 +56,7 @@ use codex_core::protocol::ViewImageToolCallEvent; use codex_core::protocol::WarningEvent; use codex_core::protocol::WebSearchBeginEvent; use codex_core::protocol::WebSearchEndEvent; +use codex_protocol::AgentId; use codex_protocol::ConversationId; use codex_protocol::parse_command::ParsedCommand; use codex_protocol::user_input::UserInput; @@ -81,6 +86,8 @@ use crate::bottom_pane::InputResult; use crate::bottom_pane::SelectionAction; use crate::bottom_pane::SelectionItem; use crate::bottom_pane::SelectionViewParams; +use crate::bottom_pane::SubagentDisplayEntry; +use crate::bottom_pane::SubagentDisplayEntryKind; use crate::bottom_pane::custom_prompt_view::CustomPromptView; use crate::bottom_pane::popup_consts::standard_popup_hint_line; use crate::clipboard_paste::paste_image_to_temp_png; @@ -88,6 +95,7 @@ use crate::diff_render::display_path_for; use crate::exec_cell::CommandOutput; use crate::exec_cell::ExecCell; use crate::exec_cell::new_active_exec_command; +use crate::exec_cell::parse_subagent_call; use crate::get_git_diff::get_git_diff; use crate::history_cell; use crate::history_cell::AgentMessageCell; @@ -105,6 +113,8 @@ use crate::slash_command::SlashCommand; use crate::status::RateLimitSnapshotDisplay; use crate::text_formatting::truncate_text; use crate::tui::FrameRequester; +use codex_protocol::models::ResponseItem; +use serde_json::Value; mod interrupts; use self::interrupts::InterruptManager; mod agent; @@ -137,6 +147,7 @@ struct RunningCommand { command: Vec, parsed_cmd: Vec, source: ExecCommandSource, + is_user_shell_command: bool, } const RATE_LIMIT_WARNING_THRESHOLDS: [f64; 3] = [75.0, 90.0, 95.0]; @@ -286,6 +297,7 @@ pub(crate) struct ChatWidget { suppress_session_configured_redraw: bool, // User messages queued while a turn is in progress queued_user_messages: VecDeque, + subagent_states: HashMap, // Pending notification to show when unfocused on next Draw pending_notification: Option, // Simple review mode flag; used to adjust layout and banners. @@ -325,6 +337,46 @@ impl From<&str> for UserMessage { } } +#[derive(Clone)] +struct SubagentUiState { + agent_id: AgentId, + session_id: ConversationId, + status: SubagentLifecycleStatus, + label: Option, + summary: Option, + reasoning_header: Option, + started_at_ms: i64, + pending_messages: usize, + pending_interrupts: usize, +} + +impl From for SubagentUiState { + fn from(summary: SubagentSummary) -> Self { + Self { + agent_id: summary.agent_id, + session_id: summary.session_id, + status: summary.status, + label: summary.label, + summary: summary.summary, + reasoning_header: summary.reasoning_header, + started_at_ms: summary.started_at_ms, + pending_messages: summary.pending_messages, + pending_interrupts: summary.pending_interrupts, + } + } +} + +impl SubagentUiState { + fn is_active(&self) -> bool { + matches!( + self.status, + SubagentLifecycleStatus::Queued + | SubagentLifecycleStatus::Running + | SubagentLifecycleStatus::Ready + ) + } +} + fn create_initial_user_message(text: String, image_paths: Vec) -> Option { if text.is_empty() && image_paths.is_empty() { None @@ -333,6 +385,12 @@ fn create_initial_user_message(text: String, image_paths: Vec) -> Optio } } +fn default_subagent_label(session_id: ConversationId) -> String { + let full = session_id.to_string(); + let short = full.chars().take(8).collect::(); + format!("Subagent {short}") +} + impl ChatWidget { fn flush_answer_stream_with_separator(&mut self) { if let Some(mut controller) = self.stream_controller.take() @@ -347,12 +405,225 @@ impl ChatWidget { self.bottom_pane.update_status_header(header); } + fn on_subagent_lifecycle(&mut self, event: SubagentLifecycleEvent, from_replay: bool) { + let Some(parent_id) = self.conversation_id else { + return; + }; + + if from_replay { + return; + } + + let mut changed = false; + match event { + SubagentLifecycleEvent::Created(created) => { + if created.subagent.parent_session_id != Some(parent_id) { + return; + } + let state: SubagentUiState = created.subagent.into(); + self.subagent_states.insert(state.session_id, state); + changed = true; + } + SubagentLifecycleEvent::Status(status) => { + if let Some(entry) = self.subagent_states.get_mut(&status.session_id) + && entry.agent_id == status.agent_id + && entry.status != status.status + { + entry.status = status.status; + changed = true; + } + } + SubagentLifecycleEvent::ReasoningHeader(reasoning) => { + if let Some(entry) = self.subagent_states.get_mut(&reasoning.session_id) + && entry.agent_id == reasoning.agent_id + { + entry.reasoning_header = Some(reasoning.reasoning_header); + changed = true; + } + } + SubagentLifecycleEvent::Deleted(removed) => { + let should_remove = self + .subagent_states + .get(&removed.session_id) + .map(|entry| entry.agent_id == removed.agent_id) + .unwrap_or(false); + if should_remove && self.subagent_states.remove(&removed.session_id).is_some() { + changed = true; + } + } + } + + if changed { + self.refresh_subagent_visuals(); + } + } + + fn on_agent_inbox(&mut self, event: AgentInboxEvent) { + if let Some(entry) = self.subagent_states.get_mut(&event.session_id) + && entry.agent_id == event.agent_id + && (entry.pending_messages != event.pending_messages + || entry.pending_interrupts != event.pending_interrupts) + { + entry.pending_messages = event.pending_messages; + entry.pending_interrupts = event.pending_interrupts; + self.refresh_subagent_visuals(); + } + } + + fn refresh_subagent_visuals(&mut self) { + let (entries, active_count) = self.build_subagent_display_entries(); + self.bottom_pane.update_subagent_summaries(entries); + self.bottom_pane.set_subagent_counts(active_count); + } + + fn build_subagent_display_entries(&self) -> (Vec, usize) { + if self.subagent_states.is_empty() { + return (Vec::new(), 0); + } + + let mut states: Vec = self.subagent_states.values().cloned().collect(); + states.sort_by(|a, b| { + a.started_at_ms + .cmp(&b.started_at_ms) + .then_with(|| a.session_id.to_string().cmp(&b.session_id.to_string())) + }); + + let active_count = states.iter().filter(|s| s.is_active()).count(); + let mut entries: Vec = Vec::with_capacity(states.len() + 1); + let total = states.len(); + + let mut detail_parts: Vec = Vec::new(); + let queued = states + .iter() + .filter(|s| s.status == SubagentLifecycleStatus::Queued) + .count(); + if queued > 0 { + detail_parts.push(format!("{queued} queued")); + } + let running = states + .iter() + .filter(|s| s.status == SubagentLifecycleStatus::Running) + .count(); + if running > 0 { + detail_parts.push(format!("{running} running")); + } + let ready = states + .iter() + .filter(|s| s.status == SubagentLifecycleStatus::Ready) + .count(); + if ready > 0 { + detail_parts.push(format!("{ready} ready")); + } + let idle = states + .iter() + .filter(|s| s.status == SubagentLifecycleStatus::Idle) + .count(); + if idle > 0 { + detail_parts.push(format!("{idle} idle")); + } + let failed = states + .iter() + .filter(|s| s.status == SubagentLifecycleStatus::Failed) + .count(); + if failed > 0 { + detail_parts.push(format!("{failed} failed")); + } + let canceled = states + .iter() + .filter(|s| s.status == SubagentLifecycleStatus::Canceled) + .count(); + if canceled > 0 { + detail_parts.push(format!("{canceled} canceled")); + } + let pending_interrupts_total: usize = states.iter().map(|s| s.pending_interrupts).sum(); + if pending_interrupts_total > 0 { + detail_parts.push(format!( + "{pending_interrupts_total} interrupt{}", + if pending_interrupts_total == 1 { + "" + } else { + "s" + } + )); + } + let pending_messages_total: usize = states.iter().map(|s| s.pending_messages).sum(); + if pending_messages_total > 0 { + detail_parts.push(format!( + "{pending_messages_total} pending msg{}", + if pending_messages_total == 1 { "" } else { "s" } + )); + } + + entries.push(SubagentDisplayEntry { + kind: SubagentDisplayEntryKind::Summary, + label: format!("{total} subagent{}", if total == 1 { "" } else { "s" }), + detail: if detail_parts.is_empty() { + None + } else { + Some(detail_parts.join(" • ")) + }, + status: None, + }); + + for state in states { + let mut label = state.label.clone(); + if label.as_ref().map(|s| s.trim().is_empty()).unwrap_or(true) { + label = Some(default_subagent_label(state.session_id)); + } + let mut detail_segments: Vec = Vec::new(); + if state.pending_interrupts > 0 { + detail_segments.push(format!( + "{} interrupt{}", + state.pending_interrupts, + if state.pending_interrupts == 1 { + "" + } else { + "s" + } + )); + } + if state.pending_messages > 0 { + detail_segments.push(format!( + "{} pending msg{}", + state.pending_messages, + if state.pending_messages == 1 { "" } else { "s" } + )); + } + if let Some(text) = state + .reasoning_header + .clone() + .or_else(|| state.summary.clone()) + { + detail_segments.push(truncate_text(&text, 160)); + } + let detail = if detail_segments.is_empty() { + None + } else { + Some(detail_segments.join(" • ")) + }; + + let label_text = label.unwrap_or_else(|| default_subagent_label(state.session_id)); + let decorated_label = format!("[#{}] {}", state.agent_id, label_text); + + entries.push(SubagentDisplayEntry { + kind: SubagentDisplayEntryKind::Item, + label: decorated_label, + detail, + status: Some(state.status), + }); + } + + (entries, active_count) + } + // --- Small event handlers --- fn on_session_configured(&mut self, event: codex_core::protocol::SessionConfiguredEvent) { self.bottom_pane .set_history_metadata(event.history_log_id, event.history_entry_count); self.conversation_id = Some(event.session_id); self.current_rollout_path = Some(event.rollout_path.clone()); + self.subagent_states.clear(); + self.refresh_subagent_visuals(); let initial_messages = event.initial_messages.clone(); let model_for_header = event.model.clone(); self.session_header.set_model(&model_for_header); @@ -864,6 +1135,31 @@ impl ChatWidget { self.set_status_header(message); } + fn on_raw_response_item(&mut self, ev: codex_core::protocol::RawResponseItemEvent) { + if let ResponseItem::FunctionCallOutput { output, .. } = ev.item { + if let Ok(value) = serde_json::from_str::(&output.content) { + if value + .get("injected") + .and_then(Value::as_bool) + .unwrap_or(false) + { + if let Some(msg) = value + .get("messages") + .and_then(Value::as_array) + .and_then(|arr| arr.first()) + .and_then(|m| m.get("prompt")) + .and_then(Value::as_str) + { + let cell = + history_cell::new_info_event(format!("subagent await: {msg}"), None); + self.add_to_history(cell); + self.request_redraw(); + } + } + } + } + } + /// Periodic tick to commit at most one queued line to history with a small delay, /// animating the output. pub(crate) fn on_commit_tick(&mut self) { @@ -938,14 +1234,21 @@ impl ChatWidget { pub(crate) fn handle_exec_end_now(&mut self, ev: ExecCommandEndEvent) { let running = self.running_commands.remove(&ev.call_id); - let (command, parsed, source) = match running { - Some(rc) => (rc.command, rc.parsed_cmd, rc.source), + let (command, parsed, source, is_user_shell_command) = match running { + Some(rc) => ( + rc.command, + rc.parsed_cmd, + rc.source, + rc.is_user_shell_command, + ), None => ( vec![ev.call_id.clone()], Vec::new(), ExecCommandSource::Agent, + false, ), }; + let subagent = parse_subagent_call(&command); let is_unified_exec_interaction = matches!(source, ExecCommandSource::UnifiedExecInteraction); @@ -960,9 +1263,11 @@ impl ChatWidget { ev.call_id.clone(), command, parsed, + subagent, source, None, self.config.animations, + is_user_shell_command, ))); } @@ -1041,12 +1346,15 @@ impl ChatWidget { pub(crate) fn handle_exec_begin_now(&mut self, ev: ExecCommandBeginEvent) { // Ensure the status indicator is visible while the command runs. + let is_user_shell_command = + ev.is_user_shell_command || matches!(ev.source, ExecCommandSource::UserShell); self.running_commands.insert( ev.call_id.clone(), RunningCommand { command: ev.command.clone(), parsed_cmd: ev.parsed_cmd.clone(), source: ev.source, + is_user_shell_command, }, ); let interaction_input = ev.interaction_input.clone(); @@ -1060,19 +1368,24 @@ impl ChatWidget { ev.parsed_cmd.clone(), ev.source, interaction_input.clone(), + is_user_shell_command, ) { *cell = new_exec; } else { self.flush_active_cell(); + let subagent = parse_subagent_call(&ev.command); + self.active_cell = Some(Box::new(new_active_exec_command( ev.call_id.clone(), ev.command.clone(), ev.parsed_cmd, + subagent, ev.source, interaction_input, self.config.animations, + is_user_shell_command, ))); } @@ -1179,6 +1492,7 @@ impl ChatWidget { retry_status_header: None, conversation_id: None, queued_user_messages: VecDeque::new(), + subagent_states: HashMap::new(), show_welcome_banner: true, suppress_session_configured_redraw: false, pending_notification: None, @@ -1254,6 +1568,7 @@ impl ChatWidget { retry_status_header: None, conversation_id: None, queued_user_messages: VecDeque::new(), + subagent_states: HashMap::new(), show_welcome_banner: true, suppress_session_configured_redraw: true, pending_notification: None, @@ -1719,8 +2034,18 @@ impl ChatWidget { self.on_entered_review_mode(review_request) } EventMsg::ExitedReviewMode(review) => self.on_exited_review_mode(review), - EventMsg::RawResponseItem(_) - | EventMsg::ItemStarted(_) + EventMsg::SubagentLifecycle(ev) => self.on_subagent_lifecycle(ev, from_replay), + EventMsg::AgentInbox(ev) => { + if !from_replay { + self.on_agent_inbox(ev); + } + } + EventMsg::RawResponseItem(ev) => { + if !from_replay { + self.on_raw_response_item(ev); + } + } + EventMsg::ItemStarted(_) | EventMsg::ItemCompleted(_) | EventMsg::AgentMessageContentDelta(_) | EventMsg::ReasoningContentDelta(_) diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 61e23fb3fc..7a271d7fb2 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -12,11 +12,14 @@ use codex_core::CodexAuth; use codex_core::config::Config; use codex_core::config::ConfigOverrides; use codex_core::config::ConfigToml; +use codex_core::config::OPENAI_DEFAULT_MODEL; +use codex_core::protocol::AgentInboxEvent; use codex_core::protocol::AgentMessageDeltaEvent; use codex_core::protocol::AgentMessageEvent; use codex_core::protocol::AgentReasoningDeltaEvent; use codex_core::protocol::AgentReasoningEvent; use codex_core::protocol::ApplyPatchApprovalRequestEvent; +use codex_core::protocol::AskForApproval; use codex_core::protocol::BackgroundEventEvent; use codex_core::protocol::Event; use codex_core::protocol::EventMsg; @@ -36,6 +39,14 @@ use codex_core::protocol::ReviewLineRange; use codex_core::protocol::ReviewOutputEvent; use codex_core::protocol::ReviewRequest; use codex_core::protocol::StreamErrorEvent; +use codex_core::protocol::SubagentCreatedEvent; +use codex_core::protocol::SubagentLifecycleEvent; +use codex_core::protocol::SubagentLifecycleOrigin; +use codex_core::protocol::SubagentLifecycleStatus; +use codex_core::protocol::SubagentReasoningHeaderEvent; +use codex_core::protocol::SubagentRemovedEvent; +use codex_core::protocol::SubagentStatusEvent; +use codex_core::protocol::SubagentSummary; use codex_core::protocol::TaskCompleteEvent; use codex_core::protocol::TaskStartedEvent; use codex_core::protocol::TokenCountEvent; @@ -56,6 +67,9 @@ use crossterm::event::KeyEvent; use crossterm::event::KeyModifiers; use insta::assert_snapshot; use pretty_assertions::assert_eq; +use std::fs::File; +use std::io::BufRead; +use std::io::BufReader; use std::path::PathBuf; use tempfile::NamedTempFile; use tempfile::tempdir; @@ -77,6 +91,39 @@ fn test_config() -> Config { .expect("config") } +// Backward-compat shim for older session logs that predate the +// `formatted_output` field on ExecCommandEnd events. +fn upgrade_event_payload_for_tests(mut payload: serde_json::Value) -> serde_json::Value { + if let Some(obj) = payload.as_object_mut() + && let Some(msg) = obj.get_mut("msg") + && let Some(m) = msg.as_object_mut() + { + let ty = m.get("type").and_then(|v| v.as_str()).unwrap_or(""); + if ty == "exec_command_end" { + let stdout = m.get("stdout").and_then(|v| v.as_str()).unwrap_or(""); + let stderr = m.get("stderr").and_then(|v| v.as_str()).unwrap_or(""); + let aggregated = if stderr.is_empty() { + stdout.to_string() + } else { + format!("{stdout}{stderr}") + }; + if !m.contains_key("formatted_output") { + m.insert( + "formatted_output".to_string(), + serde_json::Value::String(aggregated.clone()), + ); + } + if !m.contains_key("aggregated_output") { + m.insert( + "aggregated_output".to_string(), + serde_json::Value::String(aggregated), + ); + } + } + } + payload +} + fn snapshot(percent: f64) -> RateLimitSnapshot { RateLimitSnapshot { primary: Some(RateLimitWindow { @@ -369,6 +416,7 @@ fn make_chatwidget_manual() -> ( frame_requester: FrameRequester::test_dummy(), show_welcome_banner: true, queued_user_messages: VecDeque::new(), + subagent_states: HashMap::new(), suppress_session_configured_redraw: false, pending_notification: None, is_review_mode: false, @@ -724,6 +772,7 @@ fn begin_exec_with_source( cwd, parsed_cmd, source, + is_user_shell_command: false, interaction_input, }; chat.handle_codex_event(Event { @@ -757,6 +806,7 @@ fn end_exec( parsed_cmd, source, interaction_input, + .. } = begin_event; chat.handle_codex_event(Event { id: call_id.clone(), @@ -787,6 +837,30 @@ fn active_blob(chat: &ChatWidget) -> String { lines_to_single_string(&lines) } +fn open_fixture(name: &str) -> File { + // 1) Prefer fixtures within this crate + { + let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + p.push("tests"); + p.push("fixtures"); + p.push(name); + if let Ok(f) = File::open(&p) { + return f; + } + } + // 2) Fallback to parent (workspace root) + { + let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + p.push(".."); + p.push(name); + if let Ok(f) = File::open(&p) { + return f; + } + } + // 3) Last resort: CWD + File::open(name).expect("open fixture file") +} + #[test] fn empty_enter_during_task_does_not_queue() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(); @@ -966,6 +1040,175 @@ fn exec_history_cell_shows_working_then_completed() { ); } +#[test] +fn subagent_lifecycle_updates_bottom_pane() { + let (mut chat, mut _rx, _ops) = make_chatwidget_manual(); + let parent_id = ConversationId::new(); + chat.conversation_id = Some(parent_id); + chat.on_task_started(); + + let child_id = ConversationId::new(); + let summary = SubagentSummary { + agent_id: 1, + parent_agent_id: Some(0), + session_id: child_id, + parent_session_id: Some(parent_id), + origin: SubagentLifecycleOrigin::Fork, + status: SubagentLifecycleStatus::Running, + label: Some("Docs sweep".to_string()), + summary: Some("Rewrite md files".to_string()), + reasoning_header: None, + started_at_ms: 42, + pending_messages: 0, + pending_interrupts: 0, + }; + + chat.dispatch_event_msg( + Some("created".into()), + EventMsg::SubagentLifecycle(SubagentLifecycleEvent::Created(SubagentCreatedEvent { + subagent: summary, + })), + false, + ); + + assert_eq!(chat.bottom_pane.subagent_count(), 1); + assert_eq!(chat.bottom_pane.subagent_entries().len(), 2); + + chat.dispatch_event_msg( + Some("header".into()), + EventMsg::SubagentLifecycle(SubagentLifecycleEvent::ReasoningHeader( + SubagentReasoningHeaderEvent { + agent_id: 1, + session_id: child_id, + reasoning_header: "Scanning tests".to_string(), + }, + )), + false, + ); + let entries = chat.bottom_pane.subagent_entries(); + assert_eq!(entries[1].detail.as_deref(), Some("Scanning tests")); + + chat.dispatch_event_msg( + Some("status".into()), + EventMsg::SubagentLifecycle(SubagentLifecycleEvent::Status(SubagentStatusEvent { + agent_id: 1, + session_id: child_id, + status: SubagentLifecycleStatus::Idle, + })), + false, + ); + assert_eq!(chat.bottom_pane.subagent_count(), 0); + + chat.dispatch_event_msg( + Some("deleted".into()), + EventMsg::SubagentLifecycle(SubagentLifecycleEvent::Deleted(SubagentRemovedEvent { + agent_id: 1, + session_id: child_id, + })), + false, + ); + assert!(chat.bottom_pane.subagent_entries().is_empty()); +} + +#[test] +fn replayed_subagent_events_are_ignored() { + let (mut chat, mut _rx, _ops) = make_chatwidget_manual(); + let parent_id = ConversationId::new(); + chat.conversation_id = Some(parent_id); + + let child_id = ConversationId::new(); + let summary = SubagentSummary { + agent_id: 1, + parent_agent_id: Some(0), + session_id: child_id, + parent_session_id: Some(parent_id), + origin: SubagentLifecycleOrigin::Spawn, + status: SubagentLifecycleStatus::Running, + label: None, + summary: None, + reasoning_header: None, + started_at_ms: 100, + pending_messages: 0, + pending_interrupts: 0, + }; + + chat.dispatch_event_msg( + None, + EventMsg::SubagentLifecycle(SubagentLifecycleEvent::Created(SubagentCreatedEvent { + subagent: summary, + })), + true, + ); + + assert!(chat.bottom_pane.subagent_entries().is_empty()); + assert_eq!(chat.bottom_pane.subagent_count(), 0); +} + +#[test] +fn agent_inbox_updates_pending_counts() { + let (mut chat, mut _rx, _ops) = make_chatwidget_manual(); + let parent_id = ConversationId::new(); + chat.conversation_id = Some(parent_id); + + let child_id = ConversationId::new(); + let summary = SubagentSummary { + agent_id: 1, + parent_agent_id: Some(0), + session_id: child_id, + parent_session_id: Some(parent_id), + origin: SubagentLifecycleOrigin::Spawn, + status: SubagentLifecycleStatus::Running, + label: Some("Docs sweep".to_string()), + summary: None, + reasoning_header: None, + started_at_ms: 100, + pending_messages: 0, + pending_interrupts: 0, + }; + + chat.dispatch_event_msg( + None, + EventMsg::SubagentLifecycle(SubagentLifecycleEvent::Created(SubagentCreatedEvent { + subagent: summary, + })), + false, + ); + + chat.dispatch_event_msg( + None, + EventMsg::AgentInbox(AgentInboxEvent { + agent_id: 1, + session_id: child_id, + pending_messages: 2, + pending_interrupts: 1, + }), + false, + ); + + let entries = chat.bottom_pane.subagent_entries(); + assert_eq!(entries.len(), 2); + let summary_entry = &entries[0]; + let detail = summary_entry.detail.as_deref().expect("summary detail"); + assert!( + detail.contains("1 interrupt"), + "summary should include interrupt count: {detail}" + ); + assert!( + detail.contains("2 pending msgs"), + "summary should include pending message count: {detail}" + ); + let agent_entry = &entries[1]; + let detail = agent_entry.detail.as_deref().expect("agent detail"); + assert!( + detail.contains("1 interrupt"), + "agent detail should include interrupt count: {detail}" + ); + assert!( + detail.contains("2 pending msgs"), + "agent detail should include pending msg count: {detail}" + ); +} + #[test] fn exec_history_cell_shows_working_then_failed() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(); @@ -1016,6 +1259,59 @@ fn exec_history_shows_unified_exec_startup_commands() { ); } +#[test] +fn subagent_tool_calls_render_as_ran_entries() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(); + let call_id = "sub-call-1"; + let command = vec!["subagent_spawn".to_string(), "label=docs".to_string()]; + let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")); + + chat.handle_codex_event(Event { + id: call_id.to_string(), + msg: EventMsg::ExecCommandBegin(ExecCommandBeginEvent { + call_id: call_id.to_string(), + turn_id: "turn-1".to_string(), + command: command.clone(), + cwd: cwd.clone(), + parsed_cmd: Vec::new(), + source: ExecCommandSource::Agent, + is_user_shell_command: false, + interaction_input: None, + }), + }); + + chat.handle_codex_event(Event { + id: call_id.to_string(), + msg: EventMsg::ExecCommandEnd(ExecCommandEndEvent { + call_id: call_id.to_string(), + turn_id: "turn-1".to_string(), + command, + cwd, + parsed_cmd: Vec::new(), + source: ExecCommandSource::Agent, + interaction_input: None, + stdout: String::new(), + stderr: String::new(), + aggregated_output: "spawned agent #2".to_string(), + exit_code: 0, + duration: std::time::Duration::from_millis(8), + formatted_output: "spawned agent #2".to_string(), + }), + }); + + let cells = drain_insert_history(&mut rx); + assert_eq!(cells.len(), 1, "expected a single exec history cell"); + let rendered = lines_to_single_string(&cells[0]); + assert!( + rendered.contains("Ran subagent_spawn"), + "expected command header in history cell: {rendered}" + ); + assert!( + rendered.contains("spawned agent #2"), + "expected tool output to be rendered: {rendered}" + ); +} + /// Selecting the custom prompt option from the review popup sends /// OpenReviewCustomPrompt to the app event channel. #[test] @@ -1832,6 +2128,168 @@ fn disabled_slash_command_while_task_running_snapshot() { let blob = lines_to_single_string(cells.last().unwrap()); assert_snapshot!(blob); } +#[tokio::test] +async fn binary_size_transcript_snapshot() { + // the snapshot in this test depends on gpt-5-codex. Skip for now. We will consider + // creating snapshots for other models in the future. + if OPENAI_DEFAULT_MODEL != "gpt-5-codex" { + return; + } + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(); + + // Set up a VT100 test terminal to capture ANSI visual output + let width: u16 = 80; + let height: u16 = 2000; + let viewport = Rect::new(0, height - 1, width, 1); + let backend = VT100Backend::new(width, height); + let mut terminal = crate::custom_terminal::Terminal::with_options(backend) + .expect("failed to construct terminal"); + terminal.set_viewport_area(viewport); + + // Replay the recorded session into the widget and collect transcript + let file = open_fixture("binary-size-log.jsonl"); + let reader = BufReader::new(file); + let mut transcript = String::new(); + let mut has_emitted_history = false; + + for line in reader.lines() { + let line = line.expect("read line"); + if line.trim().is_empty() || line.starts_with('#') { + continue; + } + let Ok(v): Result = serde_json::from_str(&line) else { + continue; + }; + let Some(dir) = v.get("dir").and_then(|d| d.as_str()) else { + continue; + }; + if dir != "to_tui" { + continue; + } + let Some(kind) = v.get("kind").and_then(|k| k.as_str()) else { + continue; + }; + + match kind { + "codex_event" => { + if let Some(payload) = v.get("payload") { + let ev: Event = + serde_json::from_value(upgrade_event_payload_for_tests(payload.clone())) + .expect("parse"); + let ev = match ev { + Event { + msg: EventMsg::ExecCommandBegin(e), + .. + } => { + // Re-parse the command + let parsed_cmd = codex_core::parse_command::parse_command(&e.command); + Event { + id: ev.id, + msg: EventMsg::ExecCommandBegin(ExecCommandBeginEvent { + call_id: e.call_id.clone(), + turn_id: e.turn_id.clone(), + command: e.command, + cwd: e.cwd, + parsed_cmd, + source: ExecCommandSource::Agent, + is_user_shell_command: e.is_user_shell_command, + interaction_input: e.interaction_input.clone(), + }), + } + } + _ => ev, + }; + chat.handle_codex_event(ev); + while let Ok(app_ev) = rx.try_recv() { + if let AppEvent::InsertHistoryCell(cell) = app_ev { + let mut lines = cell.display_lines(width); + if has_emitted_history + && !cell.is_stream_continuation() + && !lines.is_empty() + { + lines.insert(0, "".into()); + } + has_emitted_history = true; + transcript.push_str(&lines_to_single_string(&lines)); + crate::insert_history::insert_history_lines(&mut terminal, lines) + .expect("Failed to insert history lines in test"); + } + } + } + } + "app_event" => { + if let Some(variant) = v.get("variant").and_then(|s| s.as_str()) + && variant == "CommitTick" + { + chat.on_commit_tick(); + while let Ok(app_ev) = rx.try_recv() { + if let AppEvent::InsertHistoryCell(cell) = app_ev { + let mut lines = cell.display_lines(width); + if has_emitted_history + && !cell.is_stream_continuation() + && !lines.is_empty() + { + lines.insert(0, "".into()); + } + has_emitted_history = true; + transcript.push_str(&lines_to_single_string(&lines)); + crate::insert_history::insert_history_lines(&mut terminal, lines) + .expect("Failed to insert history lines in test"); + } + } + } + } + _ => {} + } + } + + // Build the final VT100 visual by parsing the ANSI stream. Trim trailing spaces per line + // and drop trailing empty lines so the shape matches the ideal fixture exactly. + let screen = terminal.backend().vt100().screen(); + let mut lines: Vec = Vec::with_capacity(height as usize); + for row in 0..height { + let mut s = String::with_capacity(width as usize); + for col in 0..width { + if let Some(cell) = screen.cell(row, col) { + if let Some(ch) = cell.contents().chars().next() { + s.push(ch); + } else { + s.push(' '); + } + } else { + s.push(' '); + } + } + // Trim trailing spaces to match plain text fixture + lines.push(s.trim_end().to_string()); + } + while lines.last().is_some_and(std::string::String::is_empty) { + lines.pop(); + } + // Consider content only after the last session banner marker. Skip the transient + // 'thinking' header if present, and start from the first non-empty content line + // that follows. This keeps the snapshot stable across sessions. + const MARKER_PREFIX: &str = "To get started, describe a task or try one of these commands:"; + let last_marker_line_idx = lines + .iter() + .rposition(|l| l.trim_start().starts_with(MARKER_PREFIX)) + .expect("marker not found in visible output"); + // Prefer the first assistant content line (blockquote '>' prefix) after the marker; + // fallback to the first non-empty, non-'thinking' line. + let start_idx = (last_marker_line_idx + 1..lines.len()) + .find(|&idx| lines[idx].trim_start().starts_with('•')) + .unwrap_or_else(|| { + (last_marker_line_idx + 1..lines.len()) + .find(|&idx| { + let t = lines[idx].trim_start(); + !t.is_empty() && t != "thinking" + }) + .expect("no content line found after marker") + }); + + // Snapshot the normalized visible transcript following the banner. + assert_snapshot!("binary_size_ideal_response", lines[start_idx..].join("\n")); +} // // Snapshot test: command approval modal @@ -2859,6 +3317,7 @@ fn chatwidget_exec_and_status_layout_vt100_snapshot() { cwd: cwd.clone(), parsed_cmd: parsed_cmd.clone(), source: ExecCommandSource::Agent, + is_user_shell_command: false, interaction_input: None, }), }); diff --git a/codex-rs/tui/src/exec_cell/mod.rs b/codex-rs/tui/src/exec_cell/mod.rs index 906091113e..b2f04b36c5 100644 --- a/codex-rs/tui/src/exec_cell/mod.rs +++ b/codex-rs/tui/src/exec_cell/mod.rs @@ -1,10 +1,15 @@ mod model; mod render; +#[cfg(test)] +mod tests; pub(crate) use model::CommandOutput; #[cfg(test)] pub(crate) use model::ExecCall; pub(crate) use model::ExecCell; +#[cfg(test)] +pub(crate) use model::SubagentCell; +pub(crate) use model::parse_subagent_call; pub(crate) use render::OutputLinesParams; pub(crate) use render::TOOL_CALL_MAX_LINES; pub(crate) use render::new_active_exec_command; diff --git a/codex-rs/tui/src/exec_cell/model.rs b/codex-rs/tui/src/exec_cell/model.rs index 76316968c6..2cddf2561e 100644 --- a/codex-rs/tui/src/exec_cell/model.rs +++ b/codex-rs/tui/src/exec_cell/model.rs @@ -3,6 +3,138 @@ use std::time::Instant; use codex_core::protocol::ExecCommandSource; use codex_protocol::parse_command::ParsedCommand; +use serde::Deserialize; +use serde::Serialize; + +#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] +#[serde(tag = "kind")] +pub(crate) enum SubagentCell { + Spawn { + label: String, + #[serde(default)] + model: Option, + #[serde(default)] + summary: Option, + }, + Fork { + label: String, + #[serde(default)] + model: Option, + #[serde(default)] + summary: Option, + }, + SendMessage { + label: String, + #[serde(default)] + summary: Option, + }, + List { + #[serde(default)] + count: Option, + }, + Await { + #[serde(default)] + label: Option, + #[serde(default)] + timed_out: Option, + #[serde(default)] + message: Option, + #[serde(default)] + lifecycle_status: Option, + }, + Cancel { + #[serde(default)] + label: Option, + }, + Prune { + #[serde(default)] + counts: Option, + }, + Logs { + #[serde(default)] + label: Option, + #[serde(default)] + rendered: Option, + }, + Watchdog { + #[serde(default)] + action: Option, + #[serde(default)] + interval_s: Option, + #[serde(default)] + message: Option, + }, + Raw { + text: String, + }, +} + +pub(crate) fn parse_subagent_call(command: &[String]) -> Option { + let first = command.first()?; + let trimmed = first.trim(); + + if let Some(rest) = trimmed.strip_prefix("Forked subagent") { + return Some(SubagentCell::Fork { + label: rest.trim().to_string(), + model: None, + summary: None, + }); + } + if let Some(rest) = trimmed.strip_prefix("Spawned subagent") { + return Some(SubagentCell::Spawn { + label: rest.trim().to_string(), + model: None, + summary: None, + }); + } + if let Some(rest) = trimmed.strip_prefix("Sent message to subagent") { + return Some(SubagentCell::SendMessage { + label: rest.trim().to_string(), + summary: None, + }); + } + if let Some(rest) = trimmed.strip_prefix("Awaited subagent") { + return Some(SubagentCell::Await { + label: Some(rest.trim().to_string()), + timed_out: None, + message: None, + lifecycle_status: None, + }); + } + if let Some(rest) = trimmed.strip_prefix("Canceled subagent") { + return Some(SubagentCell::Cancel { + label: Some(rest.trim().to_string()), + }); + } + if let Some(rest) = trimmed.strip_prefix("Fetched subagent logs") { + return Some(SubagentCell::Logs { + label: Some(rest.trim().to_string()), + rendered: None, + }); + } + if trimmed.starts_with("Pruned subagents") { + return Some(SubagentCell::Prune { counts: None }); + } + if trimmed.starts_with("Listed subagents") { + return Some(SubagentCell::List { count: None }); + } + if trimmed.starts_with("Started watchdog") || trimmed.starts_with("Replaced watchdog") { + return Some(SubagentCell::Watchdog { + action: None, + interval_s: None, + message: None, + }); + } + + None +} + +pub(crate) fn subagent_from_formatted_output(formatted_output: &str) -> Option { + serde_json::from_str::(formatted_output) + .ok() + .and_then(|v| v.get("subagent_render").cloned()) + .and_then(|v| serde_json::from_value::(v).ok()) +} #[derive(Clone, Debug, Default)] pub(crate) struct CommandOutput { @@ -18,8 +150,10 @@ pub(crate) struct ExecCall { pub(crate) call_id: String, pub(crate) command: Vec, pub(crate) parsed: Vec, + pub(crate) subagent: Option, pub(crate) output: Option, pub(crate) source: ExecCommandSource, + pub(crate) is_user_shell_command: bool, pub(crate) start_time: Option, pub(crate) duration: Option, pub(crate) interaction_input: Option, @@ -46,13 +180,17 @@ impl ExecCell { parsed: Vec, source: ExecCommandSource, interaction_input: Option, + is_user_shell_command: bool, ) -> Option { + let subagent = parse_subagent_call(&command); let call = ExecCall { call_id, command, parsed, + subagent, output: None, source, + is_user_shell_command, start_time: Some(Instant::now()), duration: None, interaction_input, @@ -74,6 +212,9 @@ impl ExecCell { duration: Duration, ) { if let Some(call) = self.calls.iter_mut().rev().find(|c| c.call_id == call_id) { + if let Some(subagent) = subagent_from_formatted_output(&output.formatted_output) { + call.subagent = Some(subagent); + } call.output = Some(output); call.duration = Some(duration); call.start_time = None; @@ -106,6 +247,12 @@ impl ExecCell { self.calls.iter().all(Self::is_exploring_call) } + pub(crate) fn is_subagent_cell(&self) -> bool { + self.calls + .iter() + .all(|c| Self::is_subagent_call(c) && !c.is_user_shell_command) + } + pub(crate) fn is_active(&self) -> bool { self.calls.iter().any(|c| c.output.is_none()) } @@ -137,11 +284,15 @@ impl ExecCell { ) }) } + + pub(super) fn is_subagent_call(call: &ExecCall) -> bool { + call.subagent.is_some() + } } impl ExecCall { pub(crate) fn is_user_shell_command(&self) -> bool { - matches!(self.source, ExecCommandSource::UserShell) + self.is_user_shell_command } pub(crate) fn is_unified_exec_interaction(&self) -> bool { diff --git a/codex-rs/tui/src/exec_cell/render.rs b/codex-rs/tui/src/exec_cell/render.rs index 3e434138d4..0a7cbf2268 100644 --- a/codex-rs/tui/src/exec_cell/render.rs +++ b/codex-rs/tui/src/exec_cell/render.rs @@ -3,6 +3,9 @@ use std::time::Instant; use super::model::CommandOutput; use super::model::ExecCall; use super::model::ExecCell; +use super::model::SubagentCell; +use super::model::parse_subagent_call; +use super::model::subagent_from_formatted_output; use crate::exec_command::strip_bash_lc_and_escape; use crate::history_cell::HistoryCell; use crate::render::highlight::highlight_bash_to_lines; @@ -27,6 +30,32 @@ pub(crate) const TOOL_CALL_MAX_LINES: usize = 5; const USER_SHELL_TOOL_CALL_MAX_LINES: usize = 50; const MAX_INTERACTION_PREVIEW_CHARS: usize = 80; +fn header_parts(cell: &SubagentCell) -> Option<(String, Option)> { + match cell { + SubagentCell::Fork { label, .. } => Some(("Forked subagent".into(), Some(label.clone()))), + SubagentCell::Spawn { label, .. } => Some(("Spawned subagent".into(), Some(label.clone()))), + SubagentCell::SendMessage { label, .. } => { + Some(("Sent message to subagent".into(), Some(label.clone()))) + } + SubagentCell::Await { label, .. } => Some(("Awaited subagent".into(), label.clone())), + SubagentCell::Prune { .. } => Some(("Pruned subagents".into(), None)), + SubagentCell::Logs { label, .. } => Some(( + "Fetched subagent logs".into(), + label.as_ref().map(|l| format!("from {l}")), + )), + SubagentCell::List { .. } => Some(("Listed subagents".into(), None)), + SubagentCell::Watchdog { action, .. } => { + Some(("Watchdog".into(), action.as_ref().map(|a| a.to_string()))) + } + SubagentCell::Cancel { label } => Some(("Canceled subagent".into(), label.clone())), + SubagentCell::Raw { .. } => None, + } +} + +fn subagent_header_parts(command: &[String]) -> Option<(String, Option)> { + parse_subagent_call(command).as_ref().and_then(header_parts) +} + pub(crate) struct OutputLinesParams { pub(crate) line_limit: usize, pub(crate) only_err: bool, @@ -38,17 +67,22 @@ pub(crate) fn new_active_exec_command( call_id: String, command: Vec, parsed: Vec, + subagent: Option, source: ExecCommandSource, interaction_input: Option, animations_enabled: bool, + is_user_shell_command: bool, ) -> ExecCell { + let subagent = subagent.or_else(|| parse_subagent_call(&command)); ExecCell::new( ExecCall { call_id, command, parsed, + subagent, output: None, source, + is_user_shell_command, start_time: Some(Instant::now()), duration: None, interaction_input, @@ -192,6 +226,8 @@ impl HistoryCell for ExecCell { fn display_lines(&self, width: u16) -> Vec> { if self.is_exploring_cell() { self.exploring_display_lines(width) + } else if self.is_subagent_cell() { + self.subagent_display_lines(width) } else { self.command_display_lines(width) } @@ -345,6 +381,143 @@ impl ExecCell { out } + fn subagent_display_lines(&self, _width: u16) -> Vec> { + let [call] = &self.calls.as_slice() else { + panic!("Expected exactly one call in a subagent display cell"); + }; + let bullet = if let Some(output) = &call.output { + if output.exit_code == 0 { + "•".green().bold() + } else { + "•".red().bold() + } + } else { + spinner(call.start_time, self.animations_enabled()) + }; + + let render = call + .output + .as_ref() + .and_then(|o| subagent_from_formatted_output(&o.formatted_output)) + .or_else(|| call.subagent.clone()) + .or_else(|| { + subagent_header_parts(&call.command).map(|(verb, rest)| SubagentCell::Raw { + text: format!( + "{}{}", + verb, + rest.map(|r| format!(" {r}")).unwrap_or_default() + ), + }) + }); + + let Some((verb, rest)) = render.as_ref().and_then(header_parts) else { + return vec![Line::from(vec![bullet, " ".into(), "Subagent".bold()])]; + }; + + let mut header: Vec> = vec![bullet, " ".into(), verb.bold()]; + if let Some(rest) = rest + && !rest.is_empty() + { + header.push(" ".into()); + header.push(rest.into()); + } + + let mut lines = vec![Line::from(header)]; + + if let Some(render) = render { + let mut body_lines: Vec> = Vec::new(); + match render { + SubagentCell::Spawn { model, summary, .. } + | SubagentCell::Fork { model, summary, .. } => { + if let Some(m) = model { + body_lines.push(Line::from(vec![format!("model={m}").into()])); + } + if let Some(s) = summary { + body_lines.push(Line::from(vec![format!("\"{s}\"").into()])); + } + } + SubagentCell::SendMessage { summary, .. } => { + if let Some(s) = summary { + body_lines.push(Line::from(vec![format!("\"{s}\"").into()])); + } + } + SubagentCell::List { count } => { + if let Some(count) = count { + body_lines + .push(Line::from(vec![format!("listed {count} subagents").into()])); + } + } + SubagentCell::Await { + timed_out, + message, + lifecycle_status, + .. + } => { + if timed_out.unwrap_or(false) { + body_lines.push(Line::from("Timed out")); + } else if let Some(msg) = message { + body_lines.push(Line::from(msg)); + } else if let Some(status) = lifecycle_status { + body_lines.push(Line::from(vec![format!("status={status}").into()])); + } + } + SubagentCell::Cancel { .. } => {} + SubagentCell::Prune { counts } => { + if let Some(counts) = counts { + body_lines.push(Line::from(vec![ + format!("pruned subagents {counts}").into(), + ])); + } + } + SubagentCell::Logs { rendered, .. } => { + if let Some(rendered) = rendered { + for l in rendered.lines() { + body_lines.push(Line::from(l.to_string())); + } + } + } + SubagentCell::Watchdog { + action, + interval_s, + message, + } => { + if let Some(a) = action { + body_lines.push(Line::from(vec![format!("action={a}").into()])); + } + if let Some(i) = interval_s { + body_lines.push(Line::from(vec![format!("interval={i}s").into()])); + } + if let Some(msg) = message { + body_lines.push(Line::from(vec![format!("\"{msg}\"").into()])); + } + } + SubagentCell::Raw { text } => { + body_lines.push(Line::from(text)); + } + } + + if !body_lines.is_empty() { + lines.extend(prefix_lines(body_lines, " └ ".dim(), " ".into())); + } + } else if let Some(output) = call.output.as_ref() { + let OutputLines { + lines: out_lines, .. + } = output_lines( + Some(output), + OutputLinesParams { + line_limit: USER_SHELL_TOOL_CALL_MAX_LINES, + only_err: false, + include_angle_pipe: false, + include_prefix: false, + }, + ); + let prefixed = prefix_lines(out_lines, " └ ".dim(), " ".into()); + lines.extend(prefixed); + } + + lines + } + fn command_display_lines(&self, width: u16) -> Vec> { let [call] = &self.calls.as_slice() else { panic!("Expected exactly one call in a command display cell"); diff --git a/codex-rs/tui/src/exec_cell/tests.rs b/codex-rs/tui/src/exec_cell/tests.rs new file mode 100644 index 0000000000..7b30d2549e --- /dev/null +++ b/codex-rs/tui/src/exec_cell/tests.rs @@ -0,0 +1,156 @@ +use super::*; +use crate::history_cell::HistoryCell; +use codex_core::protocol::ExecCommandSource; +use insta::assert_snapshot; + +fn render(cell: &ExecCell) -> String { + cell.display_lines(120) + .into_iter() + .map(|line| { + line.spans + .iter() + .map(|s| s.content.to_string()) + .collect::() + }) + .collect::>() + .join("\n") +} + +fn make_cell(header: &str, render: SubagentCell, exit_code: i32) -> ExecCell { + let command = vec![header.to_string()]; + let call = ExecCall { + call_id: "c1".to_string(), + subagent: Some(render), + command, + parsed: vec![], + output: Some(CommandOutput { + exit_code, + aggregated_output: String::new(), + formatted_output: String::new(), + }), + source: ExecCommandSource::Agent, + is_user_shell_command: false, + start_time: None, + duration: None, + interaction_input: None, + }; + ExecCell::new(call, true) +} + +#[test] +fn snapshot_spawn_with_model() { + let cell = make_cell( + "Spawned subagent exec-review", + SubagentCell::Spawn { + label: "exec-review".into(), + model: Some("gpt-5.1-codex-mini".into()), + summary: Some("Review exec changes".into()), + }, + 0, + ); + assert_snapshot!(render(&cell), @r###" +• Spawned subagent exec-review + └ model=gpt-5.1-codex-mini + "Review exec changes" +"###); +} + +#[test] +fn snapshot_fork_prompt_only() { + let cell = make_cell( + "Forked subagent tui-review", + SubagentCell::Fork { + label: "tui-review".into(), + model: None, + summary: Some("Review TUI widgets".into()), + }, + 0, + ); + assert_snapshot!(render(&cell), @r###" +• Forked subagent tui-review + └ "Review TUI widgets" +"###); +} + +#[test] +fn snapshot_send_message() { + let cell = make_cell( + "Sent message to subagent tui-review", + SubagentCell::SendMessage { + label: "tui-review".into(), + summary: Some("Remember stylize rules".into()), + }, + 0, + ); + assert_snapshot!(render(&cell), @r###" +• Sent message to subagent tui-review + └ "Remember stylize rules" +"###); +} + +#[test] +fn snapshot_await_complete() { + let cell = make_cell( + "Awaited subagent core-review", + SubagentCell::Await { + label: Some("core-review".into()), + timed_out: Some(false), + message: Some("Completed: \"finding summary\"".into()), + lifecycle_status: Some("completed".into()), + }, + 0, + ); + assert_snapshot!(render(&cell), @r###" +• Awaited subagent core-review + └ Completed: "finding summary" +"###); +} + +#[test] +fn snapshot_await_timeout() { + let cell = make_cell( + "Awaited subagent core-review", + SubagentCell::Await { + label: Some("core-review".into()), + timed_out: Some(true), + message: None, + lifecycle_status: Some("running".into()), + }, + 1, + ); + assert_snapshot!(render(&cell), @r###" +• Awaited subagent core-review + └ Timed out +"###); +} + +#[test] +fn snapshot_logs() { + let rendered = "Session s • status=idle • older_logs=false • at_latest=true\n2025-11-11T01:06:53.424Z Thinking: ** (1 delta)\n2025-11-11T01:06:53.442Z Reasoning summary: **Evaluating safe shell command execution**"; + let cell = make_cell( + "Fetched subagent logs from core-review", + SubagentCell::Logs { + label: Some("core-review".into()), + rendered: Some(rendered.into()), + }, + 0, + ); + assert_snapshot!(render(&cell), @r###" +• Fetched subagent logs from core-review + └ Session s • status=idle • older_logs=false • at_latest=true + 2025-11-11T01:06:53.424Z Thinking: ** (1 delta) + 2025-11-11T01:06:53.442Z Reasoning summary: **Evaluating safe shell command execution** +"###); +} + +#[test] +fn snapshot_cancel() { + let cell = make_cell( + "Canceled subagent core-review", + SubagentCell::Cancel { + label: Some("core-review".into()), + }, + 0, + ); + assert_snapshot!(render(&cell), @r###"• Canceled subagent core-review"###); +} diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index 02ab0d243b..48dc8c0b8b 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -708,7 +708,7 @@ impl SessionHeaderHistoryCell { ReasoningEffortConfig::Low => "low", ReasoningEffortConfig::Medium => "medium", ReasoningEffortConfig::High => "high", - ReasoningEffortConfig::XHigh => "xhigh", + ReasoningEffortConfig::XHigh => "x-high", ReasoningEffortConfig::None => "none", }) } @@ -1860,10 +1860,12 @@ mod tests { fn coalesces_sequential_reads_within_one_call() { // Build one exec cell with a Search followed by two Reads let call_id = "c1".to_string(); + let command = vec!["bash".into(), "-lc".into(), "echo".into()]; let mut cell = ExecCell::new( ExecCall { call_id: call_id.clone(), - command: vec!["bash".into(), "-lc".into(), "echo".into()], + subagent: None, + command, parsed: vec![ ParsedCommand::Search { query: Some("shimmer_spans".into()), @@ -1883,6 +1885,7 @@ mod tests { ], output: None, source: ExecCommandSource::Agent, + is_user_shell_command: false, start_time: Some(Instant::now()), duration: None, interaction_input: None, @@ -1908,8 +1911,10 @@ mod tests { path: None, cmd: "rg shimmer_spans".into(), }], + subagent: None, output: None, source: ExecCommandSource::Agent, + is_user_shell_command: false, start_time: Some(Instant::now()), duration: None, interaction_input: None, @@ -1930,6 +1935,7 @@ mod tests { }], ExecCommandSource::Agent, None, + false, ) .unwrap(); cell.complete_call("c2", CommandOutput::default(), Duration::from_millis(1)); @@ -1945,6 +1951,7 @@ mod tests { }], ExecCommandSource::Agent, None, + false, ) .unwrap(); cell.complete_call("c3", CommandOutput::default(), Duration::from_millis(1)); @@ -1977,8 +1984,10 @@ mod tests { path: "shimmer.rs".into(), }, ], + subagent: None, output: None, source: ExecCommandSource::Agent, + is_user_shell_command: false, start_time: Some(Instant::now()), duration: None, interaction_input: None, @@ -2001,8 +2010,10 @@ mod tests { call_id: call_id.clone(), command: vec!["bash".into(), "-lc".into(), cmd], parsed: Vec::new(), + subagent: None, output: None, source: ExecCommandSource::Agent, + is_user_shell_command: false, start_time: Some(Instant::now()), duration: None, interaction_input: None, @@ -2027,8 +2038,10 @@ mod tests { call_id: call_id.clone(), command: vec!["echo".into(), "ok".into()], parsed: Vec::new(), + subagent: None, output: None, source: ExecCommandSource::Agent, + is_user_shell_command: false, start_time: Some(Instant::now()), duration: None, interaction_input: None, @@ -2051,8 +2064,10 @@ mod tests { call_id: call_id.clone(), command: vec!["bash".into(), "-lc".into(), long], parsed: Vec::new(), + subagent: None, output: None, source: ExecCommandSource::Agent, + is_user_shell_command: false, start_time: Some(Instant::now()), duration: None, interaction_input: None, @@ -2074,8 +2089,10 @@ mod tests { call_id: call_id.clone(), command: vec!["bash".into(), "-lc".into(), cmd], parsed: Vec::new(), + subagent: None, output: None, source: ExecCommandSource::Agent, + is_user_shell_command: false, start_time: Some(Instant::now()), duration: None, interaction_input: None, @@ -2098,8 +2115,10 @@ mod tests { call_id: call_id.clone(), command: vec!["bash".into(), "-lc".into(), cmd], parsed: Vec::new(), + subagent: None, output: None, source: ExecCommandSource::Agent, + is_user_shell_command: false, start_time: Some(Instant::now()), duration: None, interaction_input: None, @@ -2122,8 +2141,10 @@ mod tests { call_id: call_id.clone(), command: vec!["bash".into(), "-lc".into(), "seq 1 10 1>&2 && false".into()], parsed: Vec::new(), + subagent: None, output: None, source: ExecCommandSource::Agent, + is_user_shell_command: false, start_time: Some(Instant::now()), duration: None, interaction_input: None, @@ -2172,8 +2193,10 @@ mod tests { call_id: call_id.clone(), command: vec!["bash".into(), "-lc".into(), long_cmd.to_string()], parsed: Vec::new(), + subagent: None, output: None, source: ExecCommandSource::Agent, + is_user_shell_command: false, start_time: Some(Instant::now()), duration: None, interaction_input: None, diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 33bd18c437..b6930b95e0 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -213,6 +213,10 @@ pub async fn run_main( base_instructions: None, developer_instructions: None, compact_prompt: None, + max_active_subagents: None, + root_agent_uses_user_messages: None, + subagent_root_inbox_autosubmit: None, + subagent_inbox_inject_before_tools: None, include_apply_patch_tool: None, show_raw_agent_reasoning: cli.oss.then_some(true), tools_web_search_request: None, diff --git a/codex-rs/tui/src/pager_overlay.rs b/codex-rs/tui/src/pager_overlay.rs index 3b47e9a70e..c2abe6c367 100644 --- a/codex-rs/tui/src/pager_overlay.rs +++ b/codex-rs/tui/src/pager_overlay.rs @@ -720,9 +720,11 @@ mod tests { "exec-1".into(), vec!["bash".into(), "-lc".into(), "ls".into()], vec![ParsedCommand::Unknown { cmd: "ls".into() }], + None, ExecCommandSource::Agent, None, true, + false, ); exec_cell.complete_call( "exec-1", diff --git a/codex-rs/tui/src/status_indicator_widget.rs b/codex-rs/tui/src/status_indicator_widget.rs index 642b9ca2b7..e52d3f571c 100644 --- a/codex-rs/tui/src/status_indicator_widget.rs +++ b/codex-rs/tui/src/status_indicator_widget.rs @@ -28,6 +28,7 @@ pub(crate) struct StatusIndicatorWidget { elapsed_running: Duration, last_resume_at: Instant, is_paused: bool, + subagent_count: usize, app_event_tx: AppEventSender, frame_requester: FrameRequester, animations_enabled: bool, @@ -62,6 +63,7 @@ impl StatusIndicatorWidget { elapsed_running: Duration::ZERO, last_resume_at: Instant::now(), is_paused: false, + subagent_count: 0, app_event_tx, frame_requester, @@ -87,6 +89,14 @@ impl StatusIndicatorWidget { self.show_interrupt_hint = visible; } + pub(crate) fn set_subagent_count(&mut self, count: usize) { + if self.subagent_count == count { + return; + } + self.subagent_count = count; + self.frame_requester.schedule_frame(); + } + #[cfg(test)] pub(crate) fn interrupt_hint_visible(&self) -> bool { self.show_interrupt_hint @@ -160,20 +170,34 @@ impl Renderable for StatusIndicatorWidget { spans.push(self.header.clone().into()); } spans.push(" ".into()); + let mut status_parts = vec![pretty_elapsed]; + if self.subagent_count > 0 { + status_parts.push(format_subagent_count(self.subagent_count)); + } + let base_status = status_parts.join(" • "); if self.show_interrupt_hint { - spans.extend(vec![ - format!("({pretty_elapsed} • ").dim(), - key_hint::plain(KeyCode::Esc).into(), - " to interrupt)".dim(), - ]); + let mut prefix = format!("({base_status}"); + prefix.push_str(" • "); + spans.push(prefix.dim()); + spans.push(key_hint::plain(KeyCode::Esc).into()); + spans.push(" to interrupt)".dim()); } else { - spans.push(format!("({pretty_elapsed})").dim()); + let status_text = format!("({base_status})"); + spans.push(status_text.dim()); } Line::from(spans).render_ref(area, buf); } } +fn format_subagent_count(count: usize) -> String { + if count == 1 { + "1 subagent".to_string() + } else { + format!("{count} subagents") + } +} + #[cfg(test)] mod tests { use super::*; @@ -181,6 +205,8 @@ mod tests { use crate::app_event_sender::AppEventSender; use ratatui::Terminal; use ratatui::backend::TestBackend; + use ratatui::buffer::Buffer; + use ratatui::layout::Rect; use std::time::Duration; use std::time::Instant; use tokio::sync::mpsc::unbounded_channel; @@ -229,6 +255,37 @@ mod tests { insta::assert_snapshot!(terminal.backend()); } + #[test] + fn renders_with_subagent_count() { + let (tx_raw, _rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let mut w = StatusIndicatorWidget::new(tx, crate::tui::FrameRequester::test_dummy(), true); + w.set_subagent_count(3); + + let area = Rect::new(0, 0, 80, 1); + let mut buf = Buffer::empty(area); + w.render(area, &mut buf); + let mut row = String::new(); + for x in 0..area.width { + row.push(buf[(x, 0)].symbol().chars().next().unwrap_or(' ')); + } + assert!( + row.contains("3 subagents"), + "count should show even when interrupt hint is visible: {row}" + ); + + w.set_interrupt_hint_visible(false); + w.render(area, &mut buf); + row.clear(); + for x in 0..area.width { + row.push(buf[(x, 0)].symbol().chars().next().unwrap_or(' ')); + } + assert!( + row.contains("3 subagents"), + "expected count when no interrupt hint: {row}" + ); + } + #[test] fn timer_pauses_when_requested() { let (tx_raw, _rx) = unbounded_channel::(); diff --git a/docs/config.md b/docs/config.md index d14f7482f2..b6e5698ecc 100644 --- a/docs/config.md +++ b/docs/config.md @@ -35,6 +35,7 @@ Optional and experimental capabilities are toggled via the `[features]` table in [features] streamable_shell = true # enable the streamable exec tool web_search_request = true # allow the model to request web searches +# subagent_tools = true # expose spawn/fork/list/await/logs/prune subagent tools # view_image_tool defaults to true; omit to keep defaults ``` @@ -48,6 +49,7 @@ Supported features: | `apply_patch_freeform` | false | Beta | Include the freeform `apply_patch` tool | | `view_image_tool` | true | Stable | Include the `view_image` tool | | `web_search_request` | false | Stable | Allow the model to issue web searches | +| `subagent_tools` | false | Experimental | Enable built-in subagent orchestration tools | | `experimental_sandbox_command_assessment` | false | Experimental | Enable model-based sandbox risk assessment | | `ghost_commit` | false | Experimental | Create a ghost commit each turn | | `enable_experimental_windows_sandbox` | false | Experimental | Use the Windows restricted-token sandbox | @@ -349,6 +351,58 @@ This is reasonable to use if Codex is running in an environment that provides it Though using this option may also be necessary if you try to use Codex in environments where its native sandboxing mechanisms are unsupported, such as older Linux kernels or on Windows. +### max_active_subagents + +Controls how many subagents (spawned or forked conversations) may run concurrently within a single Codex session. Each child keeps one slot until it is pruned or fully shut down, so this setting bounds concurrency as well as memory use. + +```toml +# allow at most eight active subagents (default) +max_active_subagents = 8 +``` + +When the limit is reached, additional `spawn`/`fork` tool calls immediately return an error telling the model to prune or await existing children before launching new work. Values below 1 are rejected, and values above 64 are clamped to 64 to prevent runaway resource use. + +### root_agent_uses_user_messages + +Controls how the root agent’s messages to a subagent are represented in the subagent’s own history. When `true` (default), root-to-subagent messages are injected as `user` turns in the child. When `false`, every cross-agent message arrives only via `subagent_await` tool results, so the child must explicitly read the tool output to see root instructions. + +### subagent_root_inbox_autosubmit + +Controls whether the root agent automatically drains its inbox (and any child +messages destined for agent `0`) at safe stopping points between model turns, +and whether it may auto-start a follow-up turn based on those messages. When +`true`: + +- At the end of each model turn for the root, Codex drains the root inbox and + injects synthetic `subagent_await` call/output pairs—complete with + `completion_status`—directly into the root transcript in timestamp order. +- If a model turn finished without any tool calls and the inbox drain produced + entries, Codex immediately launches another Responses turn so the root can + react without waiting for fresh user input. +- When the root session is otherwise idle, the drain still records a lightweight + autosubmitted turn containing the pending `subagent_await` items. This keeps + the conversation history current even before the next user-initiated turn. + +When `false`, the root must call `subagent_await` explicitly to see inbox +messages during a turn, and no autosubmitted turns are emitted while idle. + +### subagent_inbox_inject_before_tools + +Controls where synthetic `subagent_await` tool calls and outputs derived from +inbox delivery are injected relative to real tool outputs inside a turn. + +- When `false` (default), Codex records the model’s tool call and tool + output(s) for a turn first, and only then appends synthetic `subagent_await` + calls/outputs derived from inbox messages (Option A). This is closer to + training-time patterns where the model generally sees its own tool call and + result before extra context. +- When `true`, Codex records synthetic `subagent_await` calls/outputs first + and then appends tool outputs (Option B), which is closer to strict + chronological ordering when inbox messages arrive while tools are running. + +This flag only affects how Codex orders conversation items in history; it +never splices synthetic items into the middle of an in-flight streaming turn. + ### tools.\* Use the optional `[tools]` table to toggle built-in tools that the agent may call. `web_search` stays off unless you opt in, while `view_image` is now enabled by default: