diff --git a/native/codex/Cargo.lock b/native/codex/Cargo.lock index bd45bce053..cd675e0196 100644 --- a/native/codex/Cargo.lock +++ b/native/codex/Cargo.lock @@ -8054,6 +8054,7 @@ dependencies = [ "codex-protocol", "codex-sandboxing", "codex-skills-extension", + "codex-thread-store", "codex-utils-path-uri", "codex-utils-rustls-provider", "codex-web-search-extension", diff --git a/native/codex/Cargo.toml b/native/codex/Cargo.toml index 5450ac8af8..46691be6da 100644 --- a/native/codex/Cargo.toml +++ b/native/codex/Cargo.toml @@ -14,6 +14,7 @@ name = "codex-sdk-runtime" path = "src/bin/codex-sdk-runtime.rs" [dependencies] +tempfile = "3" pyo3 = { version = "0.29", features = ["extension-module", "abi3-py310"] } pyo3-async-runtimes = { version = "0.29", features = ["tokio-runtime"] } tokio = { version = "1", features = ["rt-multi-thread", "sync", "time"] } @@ -39,6 +40,7 @@ codex-mcp-extension = { git = "https://github.com/openai/codex", rev = "6ff1e1ca codex-models-manager = { git = "https://github.com/openai/codex", rev = "6ff1e1ca3b30fc8b914720681fcf5fe62e95f856" } codex-protocol = { git = "https://github.com/openai/codex", rev = "6ff1e1ca3b30fc8b914720681fcf5fe62e95f856" } codex-skills-extension = { git = "https://github.com/openai/codex", rev = "6ff1e1ca3b30fc8b914720681fcf5fe62e95f856" } +codex-thread-store = { git = "https://github.com/openai/codex", rev = "6ff1e1ca3b30fc8b914720681fcf5fe62e95f856" } codex-utils-path-uri = { git = "https://github.com/openai/codex", rev = "6ff1e1ca3b30fc8b914720681fcf5fe62e95f856" } codex-utils-rustls-provider = { git = "https://github.com/openai/codex", rev = "6ff1e1ca3b30fc8b914720681fcf5fe62e95f856" } codex-web-search-extension = { git = "https://github.com/openai/codex", rev = "6ff1e1ca3b30fc8b914720681fcf5fe62e95f856" } @@ -47,7 +49,6 @@ codex-model-provider = { git = "https://github.com/openai/codex", rev = "6ff1e1c codex-guardian-v2 = { git = "https://github.com/openai/codex", rev = "6ff1e1ca3b30fc8b914720681fcf5fe62e95f856" } [dev-dependencies] -tempfile = "3" codex-sandboxing = { git = "https://github.com/openai/codex", rev = "6ff1e1ca3b30fc8b914720681fcf5fe62e95f856" } [target.'cfg(windows)'.dependencies] diff --git a/native/codex/src/children.rs b/native/codex/src/children.rs new file mode 100644 index 0000000000..37f13a7729 --- /dev/null +++ b/native/codex/src/children.rs @@ -0,0 +1,272 @@ +//! Restrict an ephemeral tree before Core registers its collaboration tools. +use codex_core::config::{AgentRoleConfig, Config}; +use codex_extension_api::{ + ModelRequestContributor, ModelRequestInput, ModelResponseError, ModelResponseInterceptor, + ModelResponseStream, ResponseEvent, +}; +use codex_features::Feature; +use codex_protocol::config_types::WebSearchMode; +use codex_protocol::models::ResponseItem; +use codex_protocol::openai_models::{ConfigShellToolType, ModelsResponse}; +use codex_protocol::protocol::MultiAgentVersion; +use futures::{StreamExt, stream}; +use pyo3::FromPyObject; +use serde_json::json; +use std::sync::{ + Arc, OnceLock, + atomic::{AtomicUsize, Ordering}, +}; +use tempfile::TempDir; + +use crate::NativeResult; + +#[derive(FromPyObject)] +pub struct Children { + roles: Vec, + max_delegation_attempts: usize, + max_depth: i32, +} + +#[derive(FromPyObject)] +struct Role { + name: String, + description: String, + instructions: String, +} + +const DISABLED: &[Feature] = &[ + Feature::Apps, + Feature::Plugins, + Feature::CodexHooks, + Feature::CodeMode, + Feature::CodeModeOnly, + Feature::DeferredExecutor, + Feature::ShellTool, + Feature::ViewImage, + Feature::ImageGeneration, + Feature::RequestPermissionsTool, +]; + +impl Children { + pub fn budget(&self) -> NativeResult> { + let wait_close = self + .max_delegation_attempts + .checked_mul(2) + .ok_or("Codex native delegation limit is too large.")?; + Ok(Arc::new(Budget { + wait_close: Arc::new(AtomicUsize::new(wait_close)), + remaining: Arc::new(AtomicUsize::new(self.max_delegation_attempts)), + denial: Arc::default(), + })) + } + + pub fn defaults(&self) -> Vec { + let mut overrides = vec![ + "agents.enabled=true".into(), + "features.multi_agent=true".into(), + "features.multi_agent_v2={enabled=false,disable_native_tools=true}".into(), + format!( + "agents.max_concurrent_threads_per_session={}", + self.max_delegation_attempts + ), + format!("agents.max_depth={}", self.max_depth), + "tools.update_plan.enabled=false".into(), + "tools.experimental_request_user_input.enabled=false".into(), + "notify=[]".into(), + ]; + overrides.extend( + DISABLED + .iter() + .map(|feature| format!("features.{}=false", feature.key())), + ); + overrides + } + + pub fn validate(&self, config: &Config) -> NativeResult<()> { + if config.update_plan_enabled { + return Err("tools.update_plan conflicts with bounded native children.".into()); + } + if !config.ephemeral + || !config.agents_enabled + || !config.features.enabled(Feature::Collab) + || config.features.enabled(Feature::MultiAgentV2) + || DISABLED + .iter() + .any(|feature| config.features.enabled(*feature)) + || config + .mcp_servers + .get() + .values() + .any(|server| server.enabled) + || !config.multi_agent_v2.disable_native_tools + || config.agent_default_subagent_model.is_some() + || config.agent_default_subagent_reasoning_effort.is_some() + || config.agent_max_threads != Some(self.max_delegation_attempts) + || config.agent_max_depth != self.max_depth + || config.experimental_request_user_input_enabled + || config.web_search_mode.value() != WebSearchMode::Disabled + || config.notify.as_ref().is_some_and(|args| !args.is_empty()) + { + return Err("Codex configuration conflicts with bounded native children.".into()); + } + Ok(()) + } + + pub fn install(&self, config: &mut Config) -> NativeResult { + let mut builder = tempfile::Builder::new(); + builder.prefix("codex-roles-"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + builder.permissions(std::fs::Permissions::from_mode(0o700)); + } + let dir = builder + .tempdir() + .map_err(|_| "Cannot create Codex role directory.")?; + config.agent_roles.clear(); + for (index, role) in self.roles.iter().enumerate() { + let file = dir.path().join(format!("{index}.toml")); + let body = toml::to_string(&json!({"developer_instructions": role.instructions})) + .map_err(|_| "Cannot encode Codex role.")?; + std::fs::write(&file, body).map_err(|_| "Cannot write Codex role.")?; + config.agent_roles.insert( + role.name.clone(), + AgentRoleConfig { + description: Some(role.description.clone()), + config_file: Some(file), + nickname_candidates: None, + }, + ); + } + Ok(dir) + } +} + +pub(crate) const MODEL_REQUIRED: &str = "Native children require an exact V1 model. \ + Run `codex debug models` and pass a slug with multi_agent_version=v1 to provider.get_model(slug)."; + +// Core selects collaboration and Code Mode from model metadata independently of +// feature flags. Freeze one approved entry so neither refresh nor a child override +// can select a different model. +pub fn catalog( + mut catalog: ModelsResponse, + model: &str, + config: &Config, +) -> NativeResult { + catalog.models.retain(|entry| entry.slug == model); + let [entry] = catalog.models.as_mut_slice() else { + return Err(MODEL_REQUIRED.into()); + }; + if entry.multi_agent_version != Some(MultiAgentVersion::V1) { + return Err(MODEL_REQUIRED.into()); + } + // A spawn naming the same model resets effort to the catalog default. + // Keep Core's own override validation, with only the parent's effort eligible. + if let Some(effort) = &config.model_reasoning_effort { + entry.default_reasoning_level = Some(effort.clone()); + } + entry + .supported_reasoning_levels + .retain(|level| Some(&level.effort) == entry.default_reasoning_level.as_ref()); + entry.tool_mode = Some(codex_protocol::openai_models::ToolMode::Direct); + entry.supports_search_tool = false; + entry.shell_type = ConfigShellToolType::Disabled; + entry.apply_patch_tool_type = None; + entry.experimental_supported_tools.clear(); + Ok(catalog) +} + +// Only the interceptor supplies these limit tags and messages. +pub type Denial = (Option<&'static str>, &'static str); + +#[derive(Clone, Debug)] +pub struct Budget { + remaining: Arc, + wait_close: Arc, + denial: Arc>, +} + +impl Budget { + pub fn denial(&self) -> Option { + self.denial.get().copied() + } + + fn deny(&self, denial: Denial) -> ModelResponseError { + let _ = self.denial.set(denial); + ModelResponseError::InvalidRequest { + message: denial.1.to_owned(), + } + } + + fn admit(&self, item: &ResponseItem) -> Result<(), ModelResponseError> { + use ResponseItem::*; + let (remaining, error) = match item { + // Core routes V1 functions by namespace and name, never by arguments or ID. + FunctionCall { + namespace: Some(ns), + name, + .. + } if ns == "multi_agent_v1" + && matches!(name.as_str(), "wait_agent" | "close_agent") => + { + ( + &self.wait_close, + ( + Some("wait_close_attempts"), + "Codex native wait/close limit exceeded.", + ), + ) + } + Message { .. } + | AgentMessage { .. } + | Reasoning { .. } + | AdditionalTools { .. } + | FunctionCallOutput { .. } + | CustomToolCallOutput { .. } + | ToolSearchOutput { .. } + | Compaction { .. } + | ConfigurationUpdate { .. } + | CompactionTrigger { .. } + | ContextCompaction { .. } => return Ok(()), + _ => ( + &self.remaining, + ( + Some("delegation_attempts"), + "Codex native delegation limit exceeded.", + ), + ), + }; + remaining + .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |left| { + left.checked_sub(1) + }) + .map_err(|_| self.deny(error))?; + // V1 handlers cannot accept custom payloads. Fail before routing alternate forms. + if !matches!(item, FunctionCall { .. }) { + return Err(self.deny((None, "Unsupported native delegation call."))); + } + Ok(()) + } +} + +impl ModelRequestContributor for Budget { + fn request(&self, _: ModelRequestInput<'_>) -> Option> { + Some(Box::new(self.clone())) + } +} + +impl ModelResponseInterceptor for Budget { + fn intercept(self: Box, stream: ModelResponseStream) -> ModelResponseStream { + stream::try_unfold((self, stream), |(budget, mut stream)| async move { + let Some(event) = stream.next().await else { + return Ok(None); + }; + let event = event?; + if let ResponseEvent::OutputItemDone(item) = &event { + budget.admit(item)?; + } + Ok(Some((event, (budget, stream)))) + }) + .boxed() + } +} diff --git a/native/codex/src/config.rs b/native/codex/src/config.rs index fbf7b44353..02a2c8b28a 100644 --- a/native/codex/src/config.rs +++ b/native/codex/src/config.rs @@ -32,6 +32,8 @@ use serde_json::{Value, json}; type Result = std::result::Result; pub struct CoreServices { + pub budget: Option>, + pub children: Option>, pub config: Config, pub manager: Arc, pub operations: Arc, @@ -307,6 +309,8 @@ pub async fn build_services( helper_executable: PathBuf, overrides: Vec, api_key: Option, + children: Option>, + attempt: &Value, ) -> Result { codex_utils_rustls_provider::ensure_rustls_crypto_provider(); let cwd = PathBuf::from(cwd) @@ -318,6 +322,19 @@ pub async fn build_services( let home = find_codex_home().map_err(|e| e.to_string())?.to_path_buf(); let helpers = HelperPaths::prepare(helper_executable)?; let mut overrides = parse_overrides(overrides)?; + if let Some(profile) = &children { + overrides.splice(0..0, parse_overrides(profile.defaults())?); + // This manager lives for one invocation. Resolve its catalog with the + // same parent effort that prepare_config applies to the thread. + if let Some(effort) = attempt.get("reasoning_effort").filter(|v| !v.is_null()) { + override_value(&mut overrides, "model_reasoning_effort", effort.clone())?; + } + } else { + // Core's V2 feature takes precedence over agents.enabled. Disable both + // after caller overrides so no catalog can grant child dispatch. + override_value(&mut overrides, "agents.enabled", json!(false))?; + override_value(&mut overrides, "features.multi_agent_v2", json!(false))?; + } // These are the provider's defaults, preceding caller overrides. overrides.splice( 0..0, @@ -417,6 +434,24 @@ pub async fn build_services( .await .map_err(|e| e.to_string())?; } + let mut models = build_models_manager(&config, auth.clone()); + if let Some(profile) = &children { + profile.validate(&config)?; + let name = attempt["model"] + .as_str() + .ok_or(crate::children::MODEL_REQUIRED)?; + let catalog = models + .raw_model_catalog( + codex_models_manager::manager::RefreshStrategy::OnlineIfUncached, + config.http_client_factory(), + ) + .await; + models = Arc::new(codex_models_manager::manager::StaticModelsManager::new( + Some(auth.clone()), + crate::children::catalog(catalog, name, &config)?, + codex_models_manager::ModelOrigin::ExplicitConfig, + )); + } let paths = ExecServerRuntimeOptions::from_optional_paths( config.codex_self_exe.clone(), config.codex_linux_sandbox_exe.clone(), @@ -435,7 +470,11 @@ pub async fn build_services( .await .map_err(|e| e.to_string())?, ); - let state_db = init_state_db(&config).await; + let state_db = if children.is_some() { + None + } else { + init_state_db(&config).await + }; let installation_id = resolve_installation_id(&config.codex_home) .await .map_err(|e| e.to_string())?; @@ -449,6 +488,10 @@ pub async fn build_services( "codex-code-mode-host" }); let operations = Arc::new(crate::operation_tracing::Observers::default()); + let budget = children + .as_ref() + .map(|profile| profile.budget()) + .transpose()?; let manager = Arc::new_cyclic(|weak| { let mut extensions = ExtensionRegistryBuilder::::new(); extensions.model_request_contributor(operations.clone()); @@ -484,10 +527,14 @@ pub async fn build_services( shadow_selection_enabled: config.features.enabled(Feature::SkillSearch), }, ); + // Register last so every emitted item passes the same tree-wide budget. + if let Some(budget) = &budget { + extensions.model_request_contributor(budget.clone()); + } let mut manager = ThreadManager::new( &config, auth.clone(), - build_models_manager(&config, auth.clone()), + models, CodexAppsToolsCache::default(), SessionSource::Exec, environments, @@ -497,7 +544,11 @@ pub async fn build_services( )), None, passthrough_image_store(), - thread_store_from_config(&config, state_db.clone()), + if children.is_some() { + Arc::new(codex_thread_store::InMemoryThreadStore::default()) + } else { + thread_store_from_config(&config, state_db.clone()) + }, local_agent_graph_store_from_state_db(state_db.as_ref()), installation_id, None, @@ -517,6 +568,8 @@ pub async fn build_services( .borrow() .source_generation; Ok(CoreServices { + budget, + children, config, manager, operations, @@ -905,6 +958,17 @@ pub async fn prepare_config(services: &CoreServices, attempt: &Value) -> Result< config.multi_agent_v2.tool_namespace.as_deref(), )?; } + if let Some(profile) = &services.children { + profile.validate(&config)?; + if config.model_reasoning_effort != services.config.model_reasoning_effort { + return Err("Codex policy changed the native child reasoning effort.".into()); + } + if config.model.as_deref() != attempt["model"].as_str() { + return Err("Codex policy changed the native child model.".into()); + } + } else if config.agents_enabled || config.features.enabled(Feature::MultiAgentV2) { + return Err("Codex policy did not disable native children.".into()); + } configure_tools( &mut config, sdk_sandbox, diff --git a/native/codex/src/lib.rs b/native/codex/src/lib.rs index 2ab1efbdb3..3a39a5edf1 100644 --- a/native/codex/src/lib.rs +++ b/native/codex/src/lib.rs @@ -1,5 +1,6 @@ //! Private, asynchronous Core bindings for the opt-in Codex model provider. mod approval_files; +mod children; mod config; mod native_approval; mod operation_tracing; @@ -45,6 +46,7 @@ fn runtime() -> &'static tokio::runtime::Runtime { /// A detached cleanup task keeps running when a Python awaitable is cancelled. struct ThreadRecord { + role_files: std::sync::Mutex>, services: Arc, thread: Arc, id: ThreadId, @@ -61,8 +63,10 @@ impl ThreadRecord { let thread = self.thread.clone(); let services = self.services.clone(); let id = self.id; + let role_files = self.role_files.lock().unwrap().take(); let operations = self.operations.clone(); let task = runtime().spawn(async move { + let _role_files = role_files; let result = async { // Each fresh root owns an independent local agent runtime. Fence that // exact tree before waiting, so native subagents cannot outlive an attempt. @@ -142,12 +146,13 @@ struct Settings { helper: PathBuf, overrides: Vec, api_key: Option, + children: Option>, } struct StartRequest { tools: String, instructions: Option, - settings: String, + settings: serde_json::Value, reply: oneshot::Sender>>, } @@ -182,12 +187,16 @@ async fn start_thread( services: Arc, request: &StartRequest, ) -> NativeResult> { - let settings = serde_json::from_str(&request.settings) - .map_err(|_| "Invalid Codex attempt settings.".to_owned())?; - let mut config = prepare_config(&services, &settings).await?; + let settings = &request.settings; + let mut config = prepare_config(&services, settings).await?; if let Some(instructions) = &request.instructions { config.developer_instructions = Some(instructions.clone()); } + let role_files = services + .children + .as_ref() + .map(|profile| profile.install(&mut config)) + .transpose()?; let values = serde_json::from_str(&request.tools) .map_err(|_| "Invalid Codex dynamic tools.".to_owned())?; let mut options = StartThreadOptions::new(config); @@ -195,6 +204,7 @@ async fn start_thread( .get("sdk_sandbox") .and_then(serde_json::Value::as_bool) == Some(true) + || services.children.is_some() { options.environments = Some(Vec::new()); } @@ -210,6 +220,7 @@ async fn start_thread( .as_str() .map(|name| tool_hooks::trusted(&created.thread, name)) .unwrap_or_default(), + role_files: std::sync::Mutex::new(role_files), model: created.session_configured.model, id: created.thread_id, thread: created.thread, @@ -236,12 +247,15 @@ async fn manager_actor( .send(Err("The Codex provider is closed.".to_owned())); continue; } + // V1 can address any thread in its manager. Never share a granted tree. if services.is_none() { match build_services( settings.cwd.clone(), settings.helper.clone(), settings.overrides.clone(), settings.api_key.clone(), + settings.children.clone(), + &request.settings, ) .await { @@ -252,17 +266,18 @@ async fn manager_actor( } } } + let host = if settings.children.is_some() { + services.take() + } else { + services.clone() + }; if closed.load(Ordering::Acquire) || request.reply.is_closed() { let _ = request .reply .send(Err("The Codex provider is closed.".to_owned())); continue; } - let result = start_thread( - services.as_ref().expect("initialized services").clone(), - &request, - ) - .await; + let result = start_thread(host.expect("initialized services"), &request).await; if let Ok(thread) = &result { threads.0.retain(|entry| { entry.cleanup.get().is_none_or(|cleanup| { @@ -332,12 +347,13 @@ struct Manager { #[pymethods] impl Manager { #[new] - #[pyo3(signature = (cwd, helper_executable, config_overrides, api_key=None))] + #[pyo3(signature = (cwd, helper_executable, config_overrides, api_key=None, *, children=None))] fn new( cwd: String, helper_executable: String, config_overrides: Vec, api_key: Option, + children: Option, ) -> Self { let (commands, receiver) = mpsc::unbounded_channel(); let closed = Arc::new(AtomicBool::new(false)); @@ -348,6 +364,7 @@ impl Manager { helper: PathBuf::from(helper_executable), overrides: config_overrides, api_key, + children: children.map(Arc::new), }, closed.clone(), )); @@ -376,7 +393,8 @@ impl Manager { .send(ManagerCommand::Start(StartRequest { tools: dynamic_tools_json, instructions, - settings: settings_json, + settings: serde_json::from_str(&settings_json) + .map_err(|_| py_error("Invalid Codex attempt settings."))?, reply, })) .map_err(|_| py_error("The Codex manager stopped unexpectedly."))?; @@ -443,6 +461,11 @@ impl Thread { Ok(tool_hooks::registered(&self.lease.thread, server)) } + #[getter] + fn delegation_error(&self) -> Option { + self.lease.services.budget.as_ref()?.denial() + } + fn inject_items<'py>( &self, py: Python<'py>, diff --git a/src/agents/memory/resumable_session.py b/src/agents/memory/resumable_session.py index 1f24e5421e..e3515e4950 100644 --- a/src/agents/memory/resumable_session.py +++ b/src/agents/memory/resumable_session.py @@ -330,7 +330,11 @@ async def _begin_run( self._validate_run(input) if current_redactor() is not None: require_clean(tool_hooks.context.context) - if self.is_paused: + if not self.is_paused: + from ..models.codex import _validate_static_children + + _validate_static_children(tool_hooks) + else: from ..run_internal.native_approvals import validate_native_restore_hooks from ..run_internal.tool_planning import ( _check_approved_functions, diff --git a/src/agents/models/_run_context.py b/src/agents/models/_run_context.py index 919656fafe..116e68bcc1 100644 --- a/src/agents/models/_run_context.py +++ b/src/agents/models/_run_context.py @@ -3,7 +3,7 @@ from collections.abc import Iterator from contextlib import contextmanager from contextvars import ContextVar -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any from .._redaction import current_redactor, redaction_scope @@ -11,12 +11,13 @@ if TYPE_CHECKING: from ..agent import Agent from ..lifecycle import RunHooks - from ..run_config import ToolExecutionConfig + from ..run_config import RunConfig, ToolExecutionConfig from ..run_context import RunContextWrapper @dataclass(frozen=True) class ModelToolHooks: + run_config: RunConfig | None = field(default=None, kw_only=True, repr=False) agent: Agent[Any] context: RunContextWrapper[Any] lifecycle: RunHooks[Any] diff --git a/src/agents/models/codex.py b/src/agents/models/codex.py index ed07ea6dfd..697c0f8f37 100644 --- a/src/agents/models/codex.py +++ b/src/agents/models/codex.py @@ -60,6 +60,12 @@ from ._codex_tracing import CodexOperationTracing from ._codex_usage import _add_sample_usage, _usage from ._run_context import ModelToolHooks, get_model_tool_hooks +from .codex_children import ( + CodexChildLimitError as CodexChildLimitError, + CodexChildren as CodexChildren, + CodexRole as CodexRole, + _delegation_error, +) from .interface import Model, ModelProvider, ModelTracing @@ -71,6 +77,54 @@ class CodexProvider(ModelProvider): command or edit for approval. The SDK session ID stays the same across workers. Supply the same SDK tool hooks on both workers. The user reviews the prepared input. Output preparation runs after execution. + + Native delegation requires `children=CodexChildren(max_delegation_attempts=1)` + or another explicit limit on this provider, even if local settings enable it. + Omit `children` for ordinary workspace tools or Python `Agent.as_tool` calls. + + To choose a model for native children, run `codex debug models` with a CLI that matches + the Codex Core revision in the SDK wheel. Use the same workspace, + credentials, provider and catalog settings. With `jq`, list candidate slugs: + + ```sh + codex debug models | jq -r '.models[] + | select(.visibility == "list" and .multi_agent_version == "v1") + | .slug' + ``` + + For API keys, add `and .supported_in_api == true` inside `select(...)`. + A catalog entry does not guarantee access. If none qualifies, there is + no listed V1 candidate. + + With a saved Codex login, pass the exact `slug` to `get_model`: + + ```python + import asyncio + + from agents import Agent, Runner + from agents.models.codex import CodexChildren, CodexProvider, CodexRole + + async def main(slug): + editor = CodexRole("editor", "Edits prose", "Return a concise rewrite.") + provider = CodexProvider(children=CodexChildren(roles=[editor], max_delegation_attempts=1)) + try: + agent = Agent(name="Manager", model=provider.get_model(slug)) + result = await Runner.run(agent, "Ask the editor to shorten 'at this point in time'.") + print(result.final_output) + finally: + await provider.aclose() + + asyncio.run(main(input("V1 model slug: "))) + ``` + + The model chooses whether to delegate. See `CodexChildren` for the attempts + that count. Limits reset on each native invocation and do not cap model + requests, tokens or cost. + This profile disables workspace tools and Code Mode. Enabled MCP servers, + SDK tools, handoffs, SDK sandboxes, update_plan, native tool hooks and saved + workspace approvals are incompatible. Core can still accept structured inputs and read local + context under the parent's permissions. Core owns child results and joins + the tree when the request ends. Child IDs cannot resume in another request. """ _supports_stored_response_id = False @@ -81,7 +135,11 @@ def __init__( cwd: str | os.PathLike[str] | None = None, config_overrides: Sequence[str] = (), api_key: str | None = None, + children: CodexChildren | None = None, ) -> None: + if children is not None and not isinstance(children, CodexChildren): + raise TypeError("children must be a CodexChildren declaration.") + self._children = children self._cwd = str(Path(cwd).resolve() if cwd is not None else Path.cwd()) self._config_overrides = tuple(config_overrides) self._api_key = api_key @@ -105,8 +163,11 @@ def _native_manager(self) -> Any: / "_codex_bin" / ("codex-sdk-runtime.exe" if os.name == "nt" else "codex-sdk-runtime") ) + options = {} + if self._children is not None: + options["children"] = self._children self._manager = native.Manager( - self._cwd, str(executable), list(self._config_overrides), self._api_key + self._cwd, str(executable), list(self._config_overrides), self._api_key, **options ) return self._manager @@ -119,10 +180,15 @@ async def aclose(self) -> None: def get_model(self, model_name: str | None) -> Model: return _CodexModel(model_name, self) + def _check_workspace_approval(self) -> None: + if self._children is not None: + raise UserError("Native children cannot resume workspace approvals.") + async def _run_approved_native_call( self, checkpoint: dict[str, Any], tracing: ModelTracing, hooks: CodexToolHooks | None ) -> str: """Run only the saved invocation, without a model turn or its old Codex home.""" + self._check_workspace_approval() if checkpoint.get("cwd") != self._cwd: raise UserError("This Codex approval belongs to a different workspace or SDK version.") @@ -214,6 +280,46 @@ def _pending_native_call( raise UserError("This Codex approval cannot safely be resumed on another worker.") +_CHILD_TOOL_CONFLICT = "Native children cannot use SDK tools, handoffs, or tool hooks." + + +def _validate_static_children(bindings: ModelToolHooks) -> None: + """Reject known conflicts before a fresh checkpoint claim, without discovery.""" + from ..agent import Agent + from ..run_internal.tool_declarations import _covered + from ..tool import FunctionTool + + config, agent = bindings.run_config, bindings.agent + if config is None or type(agent) is not Agent: + return + selected = config.model if config.model is not None else agent.model + if type(selected) is _CodexModel: + provider, name = selected._provider, selected._name + elif not isinstance(selected, Model) and type(config.model_provider) is CodexProvider: + provider, name = config.model_provider, selected + else: + return + if provider._children is None: + return + settings = agent.model_settings.resolve(config.model_settings) + if settings.tool_choice == "required": + raise UserError("Native children cannot require an SDK tool. Use tool_choice='auto'.") + policy = config.tool_execution.prepare_tool_declaration if config.tool_execution else None + if ( + any( + not isinstance(t, FunctionTool) + or (t.is_enabled is True and (policy is None or not _covered(t))) + for t in agent.tools + ) + or any(isinstance(h, Agent) or h.is_enabled is True for h in agent.handoffs) + or _uses_sdk_workspace([], bindings) + or CodexToolHooks.for_run(bindings, set()) is not None + ): + raise UserError(_CHILD_TOOL_CONFLICT) + if not name or not name.strip(): + raise UserError("Native children require an exact V1 model slug from `codex debug models`.") + + def _uses_sdk_workspace(tools: list[Tool], bindings: ModelToolHooks | None) -> bool: settings = bindings.settings if bindings else None return bool( @@ -308,6 +414,13 @@ async def _run_approved_native_call( return await self._provider._run_approved_native_call(checkpoint, tracing, hooks) def get_retry_advice(self, request: ModelRetryAdviceRequest) -> ModelRetryAdvice: + # A retry would grant a fresh allowance and expose the refusal to policy callbacks. + if isinstance(request.error, CodexChildLimitError): + from ..retry import ModelRetryNormalizedError + + return ModelRetryAdvice( + replay_safety="unsafe", normalized=ModelRetryNormalizedError(is_abort=True) + ) # Native Codex tools may have changed the workspace before a failed response. return ModelRetryAdvice(replay_safety="unsafe") @@ -407,6 +520,9 @@ async def stream_response( bindings = get_model_tool_hooks() sdk_sandbox = _uses_sdk_workspace(tools, bindings) native_hooks = None if sdk_sandbox else CodexToolHooks.for_run(bindings, identities) + children = provider._children + if children is not None and (tools or handoffs or sdk_sandbox or native_hooks): + raise UserError(_CHILD_TOOL_CONFLICT) if sdk_sandbox: system_instructions = "\n\n".join( filter( @@ -517,7 +633,9 @@ async def interrupt_when_ready() -> None: observations.bind( thread, _approval_tracing(tracing, native_hooks) if recover else tracing ) - turn_id = await thread.start_turn(json.dumps(turn_input), json.dumps(schema), recover) + turn_id = await thread.start_turn( + json.dumps(turn_input), json.dumps(schema), recover and children is None + ) response = Response( id=turn_id, created_at=time.time(), @@ -570,6 +688,7 @@ async def interrupt_when_ready() -> None: if ( message.get("turn_id") != turn_id or pending_approval is not None + or children is not None or (native_hooks is not None and not recover) or sdk_sandbox or require_sdk_call @@ -637,6 +756,8 @@ async def interrupt_when_ready() -> None: raise native_hooks.error break if kind == "error": + if children is not None and thread.delegation_error: + raise _delegation_error(*thread.delegation_error) raise RuntimeError("Codex model turn failed.") if kind == "token_count": info = message.get("info") @@ -888,6 +1009,11 @@ async def interrupt_when_ready() -> None: # Keep the attempt failure primary when joined cleanup also fails. if failure is None: raise + else: + # A parent can finish without waiting for a child that exceeded the limit. + if failure is None and children is not None and thread.delegation_error: + completed = None + raise _delegation_error(*thread.delegation_error) finally: # Pending items carry a private recovery checkpoint. observations.close(completed if pending_approval is None else None) diff --git a/src/agents/models/codex_children.py b/src/agents/models/codex_children.py new file mode 100644 index 0000000000..66e95fa390 --- /dev/null +++ b/src/agents/models/codex_children.py @@ -0,0 +1,119 @@ +"""Declarations for an isolated tree of native Codex agents.""" + +import re +from dataclasses import dataclass, field +from typing import Literal + +from ..exceptions import AgentsException, _mark_error_data_redacted + +_ChildLimit = Literal["delegation_attempts", "wait_close_attempts"] + + +class CodexChildLimitError(AgentsException): + """A native agent exceeded one of the two tree-wide attempt limits.""" + + def __init__(self, message: str, limit: _ChildLimit) -> None: + super().__init__(message) + self.limit: _ChildLimit = limit + + +def _delegation_error( + limit: _ChildLimit | None, message: str +) -> CodexChildLimitError | RuntimeError: + if limit is None: + return RuntimeError(message) + error = CodexChildLimitError(message, limit) + # Both values are fixed by the native interceptor. Keep no request data. + _mark_error_data_redacted(error) + return error + + +@dataclass(frozen=True) +class CodexRole: + """A named specialist that inherits the parent's model, reasoning effort and permissions. + + Codex uses the name and description to select a role. Its instructions cannot + restrict access. Choose permissions for the whole tree on the parent. + + To choose a specialist's model and tools in Python, use `Agent.as_tool` + without native children or a run-wide model override. + + ```python + from agents import Agent, Runner + + async def review(manager_model, editor_model, editor_tools, draft): + editor = Agent(name="Editor", model=editor_model, tools=editor_tools) + manager = Agent( + name="Manager", model=manager_model, tools=[editor.as_tool("edit", "Review a draft")] + ) + return await Runner.run(manager, f"Ask the editor to review this draft: {draft}") + ``` + + The editor returns its answer to the manager. Native child limits do not + apply to these Runner calls. + """ + + name: str + description: str + instructions: str = field(repr=False) + + def __post_init__(self) -> None: + if ( + not isinstance(self.name, str) + or not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", self.name) + or self.name.lower() in {"default", "explorer", "worker"} + ): + raise ValueError("Invalid or reserved Codex role name.") + for value in (self.description, self.instructions): + if not isinstance(value, str) or not value.strip(): + raise ValueError("Codex roles need a nonblank description and instructions.") + + +@dataclass(frozen=True, kw_only=True) +class CodexChildren: + """Allow native V1 children in a private, ephemeral tree. + + With `max_delegation_attempts=N`, the parent and all descendants share + N attempts to call spawn_agent, resume_agent, send_input or unknown functions. + Namespaced V1 wait_agent and close_agent share a separate 2N attempts. + This lets a parent wait and close after its last spawn and bounds repeated + polling. For example, N=1 allows one spawn, one wait and one close. + Failed, repeated and timed-out calls count. Closing a child refunds nothing. + Other call forms are rejected. + + Both allowances reset each native model invocation. At most + `max_delegation_attempts` children can be open at once. `max_depth` + counts generations below the root and defaults to one. An excess attempt + stops the calling thread. After cleanup, the SDK raises CodexChildLimitError + even if the parent finished without waiting. Its `limit` is + "delegation_attempts" or "wait_close_attempts". Admitted calls can still run. + + The SDK skips the model retry policy and never retries either refusal. + + Use `CodexChildren(max_delegation_attempts=1)` for built-in roles only. + The SDK copies any custom roles into a tuple. They supply instructions and + supplement the built-in default, explorer and worker roles. The model + chooses whether to delegate. Children inherit the parent's model, reasoning + effort and permissions. Set the effort on the parent. Local subagent model + or effort defaults conflict with this profile. Core rejects a spawn that + requests a different model or effort. Closed threads have no saved history + for reopening or full-history forks. These limits grant no permissions + and do not cap model requests, retries, tokens or cost. + """ + + roles: tuple[CodexRole, ...] | list[CodexRole] = () + max_delegation_attempts: int + max_depth: int = 1 + + def __post_init__(self) -> None: + if isinstance(self.roles, list): + object.__setattr__(self, "roles", tuple(self.roles)) + if not isinstance(self.roles, tuple) or any( + not isinstance(role, CodexRole) for role in self.roles + ): + raise ValueError("Provide a list or tuple of CodexRole declarations.") + if len({role.name.lower() for role in self.roles}) != len(self.roles): + raise ValueError("Duplicate Codex role name.") + for value in (self.max_delegation_attempts, self.max_depth): + if type(value) is not int or not 1 <= value <= 2**31 - 1: + raise ValueError("Codex child limits must be positive 32-bit integers.") diff --git a/src/agents/run.py b/src/agents/run.py index 5c35a7a50a..ad623974ca 100644 --- a/src/agents/run.py +++ b/src/agents/run.py @@ -780,6 +780,7 @@ async def _run_impl( context_wrapper, hooks, run_config.tool_execution, + run_config=run_config, ), run_config.tool_not_found_behavior, ) @@ -800,7 +801,11 @@ async def _run_impl( await session.begin( input, ModelToolHooks( - starting_agent, context_wrapper, hooks, run_config.tool_execution + starting_agent, + context_wrapper, + hooks, + run_config.tool_execution, + run_config=run_config, ), run_config.tool_not_found_behavior, ) @@ -3047,7 +3052,11 @@ async def run_loop() -> None: await session.begin( input, ModelToolHooks( - schema_agent, context_wrapper, hooks, run_config.tool_execution + schema_agent, + context_wrapper, + hooks, + run_config.tool_execution, + run_config=run_config, ), run_config.tool_not_found_behavior, ) diff --git a/src/agents/run_internal/native_approvals.py b/src/agents/run_internal/native_approvals.py index 6980e889a1..110cb77cc2 100644 --- a/src/agents/run_internal/native_approvals.py +++ b/src/agents/run_internal/native_approvals.py @@ -78,7 +78,7 @@ def _native_decision(context_wrapper: RunContextWrapper[Any], pending: Any) -> b def validate_native_restore_hooks(processed: Any, bindings: ModelToolHooks) -> None: - from ..models.codex import _validate_native_restore + from ..models.codex import _CodexModel, _validate_native_restore _validate_native_plan(processed) if _native_decision(bindings.context, processed.native_approvals[0]): @@ -86,6 +86,10 @@ def validate_native_restore_hooks(processed: Any, bindings: ModelToolHooks) -> N checkpoint = native_approval_checkpoint(processed.native_approvals[0].raw_item) assert checkpoint is not None _validate_native_restore([], bindings, checkpoint) + assert bindings.run_config is not None + model = get_model(bindings.agent, bindings.run_config) + if isinstance(model, _CodexModel): + model._provider._check_workspace_approval() def native_pending_step( diff --git a/tests/models/test_codex_children.py b/tests/models/test_codex_children.py new file mode 100644 index 0000000000..d782eaa7ad --- /dev/null +++ b/tests/models/test_codex_children.py @@ -0,0 +1,865 @@ +import asyncio +import json +import traceback +from threading import Barrier, Event + +import pytest +from openai.types.shared import Reasoning + +from agents import ( + Agent, + AgentsException, + ModelRetrySettings, + ModelSettings, + ResumableSession, + RunConfig, + Runner, + ToolExecutionConfig, + UserError, + function_tool, +) +from agents.models.codex import CodexChildLimitError, CodexChildren, CodexProvider, CodexRole +from agents.models.interface import ModelTracing + +from .test_codex_mutable_tool_hooks import codex_fixture, final_message +from .test_codex_pending_approval import ApprovalThread, approval, raw, response +from .test_codex_provider import native_pair, threads as threads + +pytest_plugins = ["tests.models.test_codex_mutable_tool_hooks"] + +ROLE = CodexRole("editor", "Edit the draft.", 'Return "edited".\nStay concise.') +PROFILE = CodexChildren(roles=(ROLE,), max_delegation_attempts=1) + + +@pytest.mark.parametrize("name", ["", " ", "default", "explorer", "worker", "a/b"]) +def test_invalid_child_role(name): + with pytest.raises(ValueError, match="name"): + CodexRole(name, "description", "instructions") + + +@pytest.mark.parametrize("roles", [None, "editor", [None], [ROLE, ROLE]]) +def test_invalid_roles(roles): + with pytest.raises(ValueError): + CodexChildren(roles=roles, max_delegation_attempts=1) + + +def test_builtin_roles_need_an_explicit_limit(): + assert CodexChildren(max_delegation_attempts=1).roles == () + assert CodexChildren(roles=[], max_delegation_attempts=1).roles == () + with pytest.raises(TypeError): + CodexChildren() # type: ignore[call-arg] + + +def test_invalid_child_declarations(): + with pytest.raises(ValueError, match="nonblank"): + CodexRole("editor", "description", " ") + with pytest.raises(ValueError, match="Duplicate"): + CodexChildren(roles=(ROLE, ROLE), max_delegation_attempts=1) + for limit in [0, -1, True, 1.5, 2**31]: + for field in ("max_depth", "max_delegation_attempts"): + kwargs = {"max_delegation_attempts": 1, field: limit} + with pytest.raises(ValueError, match="limits"): + CodexChildren(roles=(ROLE,), **kwargs) + + +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("conflict", ["specialist", "handoff", "hook", "missing_model", "required"]) +async def test_static_child_conflict_leaves_checkpoint_ready(streamed, conflict): + from agents.testing import ScriptedModel + from tests.memory.test_resumable_session import MemoryStore, run_agent + from tests.test_responses import get_text_message + + store = MemoryStore() + session = await ResumableSession.create(store) + before = await store.load(session.session_id) + provider = CodexProvider(children=PROFILE) + manager = Agent(name="manager", model=provider.get_model("v1")) + reviewer = Agent(name="reviewer") + config = RunConfig(tracing_disabled=True) + if conflict == "specialist": + manager.tools.append(reviewer.as_tool("review", "Check dates")) + elif conflict == "handoff": + config.model_provider = provider + config.model = "v1" + manager.handoffs.append(reviewer) + elif conflict == "required": + config.model_settings = ModelSettings(tool_choice="required") + elif conflict == "hook": + config.tool_execution = ToolExecutionConfig(prepare_tool_output=lambda call, out: out) + else: + config.model = provider.get_model(None) + with pytest.raises(UserError, match="Native children"): + await run_agent(manager, "Check", session, streamed, run_config=config) + assert await store.load(session.session_id) == before + reopened = await ResumableSession.resume(store, session.session_id) + override = RunConfig(model=ScriptedModel([[get_text_message("ok")]]), tracing_disabled=True) + result = await run_agent(manager, "Check", reopened, streamed, run_config=override) + assert result.final_output == "ok" + + +@pytest.mark.allow_call_model_methods +@pytest.mark.parametrize("streamed", [False, True]) +async def test_child_session_respects_tool_choice_override_and_withheld_function( + tmp_path, monkeypatch, model_endpoint, catalog, streamed +): + from tests.memory.test_resumable_session import MemoryStore, run_agent + + @function_tool + def publish() -> str: + raise AssertionError("Withheld tool ran") + + checks = [] + + async def omit(ctx, declaration): + checks.append(declaration.name) + return None + + port, requests, items = model_endpoint + items.append(final_message()) + provider = codex_fixture(tmp_path, port, monkeypatch, catalog, children=PROFILE) + manager = Agent( + name="manager", + model=provider.get_model("v1"), + tools=[publish], + model_settings=ModelSettings(tool_choice="required"), + ) + config = RunConfig( + tracing_disabled=True, + model_settings=ModelSettings(tool_choice="auto"), + tool_execution=ToolExecutionConfig(prepare_tool_declaration=omit), + ) + session = await ResumableSession.create(MemoryStore()) + try: + result = await run_agent(manager, "Check", session, streamed, run_config=config) + assert result.final_output == "done" + assert checks == ["publish"] + assert len(requests) == 1 + assert all(tool.get("name") != "publish" for tool in requests[0]["tools"]) + finally: + await provider.aclose() + + +@pytest.mark.parametrize("streamed", [False, True]) +async def test_dynamic_child_conflict_keeps_claim_after_enabling_once(streamed): + from tests.memory.test_resumable_session import MemoryStore, run_agent + + store = MemoryStore() + session = await ResumableSession.create(store) + checks = [] + + def enabled(ctx, agent): + checks.append(store.checkpoint(session.session_id)["status"]) + return True + + provider = CodexProvider(children=PROFILE) + tool = Agent(name="reviewer").as_tool("review", "Check dates", is_enabled=enabled) + manager = Agent(name="manager", model=provider.get_model("v1"), tools=[tool]) + with pytest.raises(UserError, match="Native children"): + await run_agent(manager, "Check", session, streamed) + assert checks == ["active"] + assert store.checkpoint(session.session_id)["status"] == "active" + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +async def test_child_incompatible_sdk_tool_rejected_without_native_start(): + @function_tool + def local() -> str: + raise AssertionError("No tool invocation expected") + + provider = CodexProvider(children=PROFILE) + try: + with pytest.raises(UserError, match="Native children"): + await Runner.run( + Agent(name="manager", model=provider.get_model(None), tools=[local]), + "draft", + run_config=RunConfig(tracing_disabled=True), + ) + finally: + await provider.aclose() + + +@pytest.mark.asyncio +async def test_native_children_reject_saved_workspace_approval_before_start(tmp_path, threads): + call, _ = native_pair(call_id="pending") + threads[0].append( + ApprovalThread(events=[raw(call), approval(), {"type": "raw_response_completed"}]) + ) + checkpoint = (await response(tmp_path)).output[0].checkpoint + provider = CodexProvider(cwd=tmp_path, children=PROFILE) + with pytest.raises(UserError, match="cannot resume workspace approvals"): + await provider._run_approved_native_call(checkpoint, ModelTracing.DISABLED, hooks=None) + assert provider._manager is None + + +@pytest.mark.asyncio +async def test_native_children_reject_unexpected_workspace_approval(tmp_path, threads): + thread = ApprovalThread(events=[approval()]) + threads[0].append(thread) + provider = CodexProvider(cwd=tmp_path, children=PROFILE) + provider._manager = CodexProvider(cwd=tmp_path)._native_manager() + try: + with pytest.raises(UserError, match="native workspace tools enabled"): + await Runner.run( + Agent(name="manager", model=provider.get_model(None)), + "draft", + run_config=RunConfig(tracing_disabled=True), + ) + assert thread.closed + finally: + await provider.aclose() + + +@pytest.mark.asyncio +async def test_provider_text_cannot_signal_a_child_limit(tmp_path, threads): + thread = ApprovalThread( + events=[{"type": "error", "message": "Codex native delegation limit exceeded."}] + ) + thread.delegation_error = None + threads[0].append(thread) + provider = CodexProvider(cwd=tmp_path, children=PROFILE) + provider._manager = CodexProvider(cwd=tmp_path)._native_manager() + try: + with pytest.raises(RuntimeError, match="Codex model turn failed") as caught: + await ask(provider) + assert not isinstance(caught.value, CodexChildLimitError) + assert thread.closed + finally: + await provider.aclose() + + +@pytest.fixture +def catalog(tmp_path): + path = tmp_path / "catalog.json" + path.write_text( + json.dumps( + { + "models": [ + { + "slug": version, + "display_name": version, + "base_instructions": "Answer briefly.", + "default_reasoning_level": "low", + "supported_reasoning_levels": [ + {"effort": level, "description": level} for level in ("low", "high") + ], + "shell_type": "unified_exec", + "visibility": "list", + "supported_in_api": True, + "priority": 1, + "support_verbosity": False, + "truncation_policy": {"mode": "tokens", "limit": 10000}, + "experimental_supported_tools": [], + "multi_agent_version": version, + "tool_mode": "code_mode_only", + "supports_search_tool": True, + "apply_patch_tool_type": "freeform", + } + for version in ("v1", "v2") + ] + } + ) + ) + return [ + f"model_catalog_json={json.dumps(str(path))}", + 'sandbox_mode="read-only"', + 'approval_policy="never"', + ] + + +async def ask(provider, model="v1", prompt="draft", *, settings=None): + result = await asyncio.wait_for( + Runner.run( + Agent( + name="manager", + model=provider.get_model(model), + model_settings=settings or ModelSettings(), + ), + prompt, + run_config=RunConfig(tracing_disabled=True), + ), + 30, + ) + assert result.final_output == "done" + + +def call(name, tag, **args): + return { + "type": "function_call", + "namespace": "multi_agent_v1", + "name": name, + "call_id": tag, + "arguments": json.dumps(args), + } + + +def user_input(request): + return json.dumps([i for i in request["input"] if i.get("role") == "user"]) + + +def outputs(request): + return { + i["call_id"]: i["output"] + for i in request["input"] + if i.get("type") == "function_call_output" + } + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +@pytest.mark.parametrize("stream", [False, True]) +@pytest.mark.parametrize( + "model,overrides", + [ + ("v1", []), + ("v1", ["agents.enabled=true", "features.multi_agent=false"]), + ("v2", ["agents.enabled=false", "features.multi_agent_v2=true"]), + ], +) +async def test_native_delegation_requires_a_provider_grant( + tmp_path, monkeypatch, model_endpoint, catalog, stream, model, overrides +): + port, requests, items = model_endpoint + provider = codex_fixture(tmp_path, port, monkeypatch, [*catalog, *overrides]) + # The Code Mode catalog can hide a callable handler from the tool list. + spawn = call("spawn_agent", "spawn", message="LEAF") + if model == "v2": + spawn = call("spawn_agent", "spawn", message="LEAF", task_name="leaf", fork_turns="none") + spawn["namespace"] = "collaboration" + items.extend([spawn, final_message(), final_message()]) + agent = Agent(name="manager", model=provider.get_model(model)) + config = RunConfig(tracing_disabled=True) + try: + if stream: + result = Runner.run_streamed(agent, "draft", run_config=config) + async for _ in result.stream_events(): + pass + else: + result = await Runner.run(agent, "draft", run_config=config) + assert result.final_output == "done" + finally: + await provider.aclose() + assert len(requests) == 2 + assert all("LEAF" not in user_input(request) for request in requests) + assert "unsupported" in outputs(requests[-1])["spawn"].lower() + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +async def test_python_agent_tool_does_not_require_native_children( + tmp_path, monkeypatch, model_endpoint, catalog +): + port, requests, items = model_endpoint + provider = codex_fixture(tmp_path, port, monkeypatch, catalog) + model = provider.get_model("v2") + editor = Agent(name="editor", model=model).as_tool("edit", "Edit a draft") + manager = Agent(name="manager", model=model, tools=[editor]) + edit = call("edit", "edit", input="REVIEW") + del edit["namespace"] + items.extend([edit, final_message(), final_message()]) + try: + result = await Runner.run(manager, "draft", run_config=RunConfig(tracing_disabled=True)) + assert result.final_output == "done" + assert len(requests) == 3 + assert "REVIEW" in user_input(requests[1]) + assert outputs(requests[-1])["edit"] == "done" + finally: + await provider.aclose() + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +@pytest.mark.parametrize( + "model,extra", + [ + (None, []), + ("v2", []), + ("unknown", []), + ("v1", ["agents.max_depth=2"]), + ("v1", ['agents.default_subagent_reasoning_effort="low"']), + ("v1", ["tools.update_plan.enabled=true"]), + ("v1", ["features.shell_tool=true"]), + ("v1", ["features.multi_agent_v2=true"]), + ], +) +async def test_unsupported_children_before_generation( + tmp_path, monkeypatch, model_endpoint, catalog, model, extra +): + port, requests, items = model_endpoint + items.append(final_message()) + provider = codex_fixture(tmp_path, port, monkeypatch, catalog + extra, children=PROFILE) + try: + with pytest.raises(RuntimeError) as exc: + await ask(provider, model) + if extra == ["tools.update_plan.enabled=true"]: + assert "tools.update_plan conflicts" in str(exc.value) + elif extra: + assert "conflict" in str(exc.value) + else: + assert str(exc.value) == ( + "Native children require an exact V1 model. Run `codex debug models` and pass " + "a slug with multi_agent_version=v1 to provider.get_model(slug)." + ) + assert not requests + finally: + await provider.aclose() + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +@pytest.mark.parametrize("spawn", [{}, {"model": "v1"}]) +async def test_native_children_at_depth_limit( + tmp_path, monkeypatch, model_endpoint, catalog, spawn +): + port, requests, items = model_endpoint + roles = [ROLE] + children = CodexChildren(roles=roles, max_delegation_attempts=2) + roles.clear() + assert children.roles == (ROLE,) + provider = codex_fixture(tmp_path, port, monkeypatch, catalog, children=children) + + def step(request): + receipts = outputs(request) + if "LEAF" in user_input(request): + if not receipts: + return call("spawn_agent", "grand", message="GRAND") + return final_message() + if not receipts: + return call("spawn_agent", "spawn", message="LEAF", agent_type=ROLE.name, **spawn) + if "wait" not in receipts: + target = json.loads(receipts["spawn"])["agent_id"] + return call("wait_agent", "wait", targets=[target], timeout_ms=10000) + return final_message() + + items.extend([step] * 5) + try: + await ask(provider, settings=ModelSettings(reasoning=Reasoning(effort="high"))) + assert len(requests) == 5 + assert all(r["model"] == "v1" and r["reasoning"]["effort"] == "high" for r in requests) + assert ROLE.description in json.dumps(requests[0]) + leaf = next(r for r in requests if "grand" in outputs(r)) + assert json.dumps(ROLE.instructions)[1:-1] in json.dumps(leaf) + assert not leaf.get("tools") + assert all(i.get("type") != "additional_tools" for i in leaf["input"]) + assert "unsupported" in outputs(leaf)["grand"].lower() + parent = outputs(requests[-1]) + assert "done" in parent["wait"] + finally: + await provider.aclose() + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +async def test_child_native_fork_reopen_and_model_selection( + tmp_path, monkeypatch, model_endpoint, catalog +): + port, requests, items = model_endpoint + provider = codex_fixture( + tmp_path, + port, + monkeypatch, + [ + *catalog, + 'model_reasoning_effort="high"', + 'agents.ambient.description="ambient specialist"', + ], + children=CodexChildren(roles=(ROLE,), max_delegation_attempts=6), + ) + child_id = "" + + def step(request): + nonlocal child_id + if "LEAF" in user_input(request): + return final_message() + receipts = outputs(request) + if not receipts: + return [ + call("spawn_agent", "switch", message="LEAF", model="v2"), + call("spawn_agent", "effort", message="LEAF", reasoning_effort="low"), + call("spawn_agent", "ambient", message="LEAF", agent_type="ambient"), + ] + if "fork" not in receipts: + return call("spawn_agent", "fork", message="LEAF", fork_context=True) + if "spawn" not in receipts: + return call("spawn_agent", "spawn", message="LEAF", agent_type=ROLE.name, model="v1") + if "wait" not in receipts: + child_id = json.loads(receipts["spawn"])["agent_id"] + return call("wait_agent", "wait", targets=[child_id], timeout_ms=10000) + if "close" not in receipts: + return call("close_agent", "close", target=child_id) + if "reopen" not in receipts: + return call("resume_agent", "reopen", id=child_id) + return final_message() + + items.extend([step] * 8) + try: + await ask(provider) + parent = outputs(requests[-1]) + assert "not found" in parent["reopen"] + assert "ambient specialist" not in json.dumps(requests[0]) + assert "unknown" in parent["ambient"].lower() + assert "Unknown model" in parent["switch"] + assert "not supported" in parent["effort"] + assert sum("LEAF" in user_input(r) for r in requests) == 1 + assert all(r["model"] == "v1" and r["reasoning"]["effort"] == "high" for r in requests) + assert "no thread" in parent["fork"] + assert "done" in parent["wait"] + assert len(requests) == 8 + items.extend([call("resume_agent", "foreign", id=child_id), final_message()]) + await ask(provider) + assert "not found" in outputs(requests[-1])["foreign"] + assert len(requests) == 10 + finally: + await provider.aclose() + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +async def test_child_native_depth_two_and_live_tree_isolation( + tmp_path, monkeypatch, model_endpoint, catalog +): + port, requests, items = model_endpoint + children = CodexChildren(roles=(ROLE,), max_delegation_attempts=2, max_depth=2) + provider = codex_fixture(tmp_path, port, monkeypatch, catalog, children=children) + started, release = Event(), Event() + child_id = "" + + def step(request): + nonlocal child_id + prompt = user_input(request) + receipts = outputs(request) + if "FOREIGN" in prompt: + if not receipts: + return call("resume_agent", "foreign", id=child_id) + release.set() + return final_message() + if "GRAND" in prompt: + assert release.wait(10) + return final_message() + if not receipts: + return call( + "spawn_agent", + "spawn", + agent_type=ROLE.name, + message="GRAND" if "LEAF" in prompt else "LEAF", + ) + if "wait" not in receipts: + target = json.loads(receipts["spawn"])["agent_id"] + if "LEAF" in prompt: + child_id = target + started.set() + return call("wait_agent", "wait", targets=[target], timeout_ms=20000) + return final_message() + + # A late completion notification can prompt one more reply per child after a wait. + items.extend([step] * 11) + root = asyncio.create_task(ask(provider)) + try: + assert await asyncio.to_thread(started.wait, 10) + await ask(provider, prompt="FOREIGN") + await root + assert any("not found" in outputs(r).get("foreign", "") for r in requests) + waits = {} + notified = set() + for request in requests: + receipts = outputs(request) + if "wait" not in receipts: + continue + target = json.loads(receipts["spawn"])["agent_id"] + completed = {"completed": "done"} + assert json.loads(receipts["wait"]) == { + "timed_out": False, + "status": {target: completed}, + } + history = request["input"] + if target not in waits: + waits[target] = history + continue + + assert target not in notified and history[:-2] == waits[target] + answer, notice = history[-2:] + assert answer["type"] == notice["type"] == "message" + assert answer["role"] == "assistant" and answer["content"] == final_message()["content"] + assert notice["role"] == "user" + (part,) = notice["content"] + start, payload, end = part["text"].splitlines() + assert (start, end) == ("", "") + assert json.loads(payload) == {"agent_path": target, "status": completed} + notified.add(target) + assert len(waits) == 2 + assert len(requests) == 9 + len(notified) + finally: + release.set() + root.cancel() + await asyncio.gather(root, return_exceptions=True) + await provider.aclose() + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +async def test_child_close_does_not_refund(tmp_path, monkeypatch, model_endpoint, catalog): + port, requests, items = model_endpoint + provider = codex_fixture( + tmp_path, port, monkeypatch, catalog, children=CodexChildren(max_delegation_attempts=1) + ) + + def step(request): + prompt = user_input(request) + if "LEAF" in prompt: + return final_message() + receipts = outputs(request) + if not receipts: + return call("spawn_agent", "spawn", message="LEAF") + target = json.loads(receipts["spawn"])["agent_id"] + if "wait" not in receipts: + return call("wait_agent", "wait", targets=[target], timeout_ms=10000) + if "close" not in receipts: + return call("close_agent", "close", target=target) + if "fresh" in prompt: + return final_message() + return call("spawn_agent", "spawn", message="REPLACEMENT") + + items.extend([step] * 10) + try: + with pytest.raises(CodexChildLimitError) as caught: + await ask(provider) + assert caught.value.limit == "delegation_attempts" + assert len(requests) == 5 + await ask(provider, prompt="fresh") + assert len(requests) == 10 + assert sum("LEAF" in user_input(r) for r in requests) == 2 + assert all("REPLACEMENT" not in user_input(r) for r in requests) + for i in (4, 9): + assert "done" in outputs(requests[i])["wait"] + assert "done" in outputs(requests[i])["close"] + finally: + await provider.aclose() + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +@pytest.mark.parametrize( + "attempt", + [ + call("resume_agent", "first", id="missing"), + call("send_input", "first", target="missing", message="continue"), + {**call("spawn_agent", "first"), "arguments": "{"}, + {**call("wait_agent", "first"), "namespace": "functions"}, + ], +) +async def test_child_failed_calls_consume_budget( + tmp_path, monkeypatch, model_endpoint, catalog, attempt +): + port, requests, items = model_endpoint + provider = codex_fixture(tmp_path, port, monkeypatch, catalog, children=PROFILE) + items.extend([attempt, call("spawn_agent", "next", message="LEAF"), final_message()]) + try: + with pytest.raises(CodexChildLimitError) as caught: + await ask(provider) + assert caught.value.limit == "delegation_attempts" + assert len(requests) == 2 + assert "LEAF" not in user_input(requests[-1]) + finally: + await provider.aclose() + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +async def test_children_share_last_delegation(tmp_path, monkeypatch, model_endpoint, catalog): + port, requests, items = model_endpoint + children = CodexChildren(roles=(ROLE,), max_delegation_attempts=3, max_depth=2) + provider = codex_fixture(tmp_path, port, monkeypatch, catalog, children=children) + siblings = Barrier(2) + + def step(request): + prompt = user_input(request) + receipts = outputs(request) + if "GRAND" in prompt: + return final_message() + if "LEAF" in prompt: + if not receipts: + siblings.wait(timeout=10) + return call("spawn_agent", "grand", message="GRAND") + names = ["grand"] + else: + names = ["one", "two"] + if not receipts: + return [call("spawn_agent", tag, message="LEAF") for tag in names] + for name in names: + if "wait" + name not in receipts: + target = json.loads(receipts[name])["agent_id"] + return call("wait_agent", "wait" + name, targets=[target], timeout_ms=10000) + return final_message() + + items.extend([step] * 9) + try: + with pytest.raises(CodexChildLimitError) as caught: + await ask(provider) + assert caught.value.limit == "delegation_attempts" + waits = [outputs(requests[-1])["wait" + tag] for tag in ("one", "two")] + assert sum("delegation limit exceeded" in result for result in waits) == 1 + assert sum("done" in result for result in waits) == 1 + assert sum("GRAND" in user_input(r) for r in requests) == 1 + assert len(requests) == 9 + finally: + siblings.abort() + await provider.aclose() + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +async def test_child_rejects_custom_payload(tmp_path, monkeypatch, model_endpoint, catalog): + port, requests, items = model_endpoint + provider = codex_fixture(tmp_path, port, monkeypatch, catalog, children=PROFILE) + items.append( + { + "type": "custom_tool_call", + "namespace": "multi_agent_v1", + "name": "close_agent", + "call_id": "first", + "input": "{}", + } + ) + try: + with pytest.raises(RuntimeError, match="Unsupported native delegation") as caught: + await ask(provider) + assert not isinstance(caught.value, CodexChildLimitError) + assert len(requests) == 1 + finally: + await provider.aclose() + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +@pytest.mark.parametrize("streamed", [False, True]) +@pytest.mark.parametrize("limit", ["delegation_attempts", "wait_close_attempts"]) +async def test_child_counts_each_item_in_one_response( + tmp_path, monkeypatch, model_endpoint, catalog, streamed, limit +): + port, requests, items = model_endpoint + provider = codex_fixture(tmp_path, port, monkeypatch, catalog, children=PROFILE) + if limit == "delegation_attempts": + items.append( + [ + call("send_input", "same", message="missing target"), + call("spawn_agent", "same", message="LEAF"), + ] + ) + else: + items.append([call("wait_agent", str(i)) for i in range(3)]) + items.append(final_message()) + + def unexpected_retry(context): + pytest.fail("A limit refusal must not reach the retry policy.") + + try: + with pytest.raises(AgentsException) as caught: + agent = Agent( + name="manager", + model=provider.get_model("v1"), + model_settings=ModelSettings( + retry=ModelRetrySettings(max_retries=1, policy=unexpected_retry) + ), + ) + config = RunConfig( + tracing_disabled=True, redact_text=lambda s: s.replace("private", "*") + ) + if streamed: + run = Runner.run_streamed(agent, "private draft", run_config=config) + async for _ in run.stream_events(): + pass + else: + await Runner.run(agent, "private draft", run_config=config) + assert isinstance(caught.value, CodexChildLimitError) + assert caught.value.run_data is None + assert caught.value.limit == limit + assert "private draft" not in "".join( + traceback.format_exception_only(type(caught.value), caught.value) + ) + assert len(requests) == 1 + finally: + await provider.aclose() + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +async def test_native_wait_and_close_share_a_finite_allowance( + tmp_path, monkeypatch, model_endpoint, catalog +): + port, requests, items = model_endpoint + provider = codex_fixture(tmp_path, port, monkeypatch, catalog, children=PROFILE) + # Even without a child, failed calls can each trigger another provider request. + attempts = [call("wait_agent", "wait"), call("close_agent", "close")] + try: + items.extend([*attempts, call("wait_agent", "again"), final_message()]) + with pytest.raises(CodexChildLimitError) as caught: + await ask(provider) + assert caught.value.limit == "wait_close_attempts" + assert len(requests) == 3 + items.clear() + items.extend([*attempts, final_message()]) + await ask(provider) + assert len(requests) == 6 + finally: + await provider.aclose() + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +async def test_native_child_uses_the_same_wait_and_close_allowance( + tmp_path, monkeypatch, model_endpoint, catalog +): + port, requests, items = model_endpoint + children = CodexChildren(roles=(ROLE,), max_delegation_attempts=1, max_depth=2) + provider = codex_fixture(tmp_path, port, monkeypatch, catalog, children=children) + + def step(request): + receipts = outputs(request) + if "LEAF" in user_input(request): + return final_message() if receipts else call("wait_agent", "empty") + if not receipts: + return call("spawn_agent", "spawn", message="LEAF") + target = json.loads(receipts["spawn"])["agent_id"] + if "wait" not in receipts: + return call("wait_agent", "wait", targets=[target], timeout_ms=10000) + return call("close_agent", "close", target=target) + + items.extend([step] * 5 + [final_message()]) + try: + with pytest.raises(CodexChildLimitError) as caught: + await ask(provider) + assert caught.value.limit == "wait_close_attempts" + assert len(requests) == 5 + assert "done" in outputs(requests[-1])["wait"] + finally: + await provider.aclose() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("streamed", [False, True]) +async def test_bounded_override_leaves_saved_approval_paused(tmp_path, monkeypatch, streamed): + from agents.memory.resumable_session import ResumableSession + from tests.memory.test_native_approval_recovery import setup_native + + agent, store, session, config, pending, calls, _ = await setup_native(tmp_path, monkeypatch) + first = await Runner.run(agent, "draft", session=session, run_config=config) + saved = store.records[session.session_id] + state = first.to_state() + state.approve(first.interruptions[0]) + provider = CodexProvider(cwd=tmp_path, children=PROFILE) + bounded = RunConfig(model=provider.get_model(None), tracing_disabled=True) + with pytest.raises(UserError, match="cannot resume workspace approvals"): + if streamed: + stream = Runner.run_streamed(agent, state, run_config=bounded) + async for _ in stream.stream_events(): + pass + else: + await Runner.run(agent, state, run_config=bounded) + assert provider._manager is None and not calls + assert store.records[session.session_id] == saved + recovered = await ResumableSession.resume(store, session.session_id) + state = await recovered.load_state(agent) + state.approve(state.get_interruptions()[0]) + result = await Runner.run(agent, state, run_config=config) + assert result.final_output == "finished" + assert calls == [pending.checkpoint] diff --git a/tests/models/test_codex_mutable_tool_hooks.py b/tests/models/test_codex_mutable_tool_hooks.py index 6ee56d4bea..3475c16277 100644 --- a/tests/models/test_codex_mutable_tool_hooks.py +++ b/tests/models/test_codex_mutable_tool_hooks.py @@ -50,14 +50,17 @@ def do_POST(self): "created_at": 1, "model": request.get("model", "gpt-5.4"), "status": "completed", - "output": [item], + "output": item if isinstance(item, list) else [item], "parallel_tool_calls": True, "tools": [], "tool_choice": "auto", } events = [ {"type": "response.created", "response": response}, - {"type": "response.output_item.done", "item": item}, + *( + {"type": "response.output_item.done", "item": value} + for value in response["output"] + ), {"type": "response.completed", "response": response}, ] body = ( @@ -93,7 +96,7 @@ def final_message(): } -def codex_fixture(tmp_path, port, monkeypatch, extra=()): +def codex_fixture(tmp_path, port, monkeypatch, extra=(), **options): if find_spec("agents.models._codex_native") is None: pytest.skip("Install the SDK's embedded Codex extension to exercise this path.") config_home = tmp_path / "codex" @@ -115,6 +118,7 @@ def codex_fixture(tmp_path, port, monkeypatch, extra=()): "model_providers.fixture.stream_max_retries=0", *extra, ], + **options, )