From 1df5a86ade9f51224fc3d9466b4103c908520c22 Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Sat, 21 Nov 2026 06:22:09 -0800 Subject: [PATCH 1/5] Add native specialist roles and delegation limits to CodexProvider --- native/codex/Cargo.lock | 1 + native/codex/Cargo.toml | 3 +- native/codex/src/children.rs | 137 ++++++++ native/codex/src/config.rs | 43 ++- native/codex/src/lib.rs | 40 ++- src/agents/models/codex.py | 24 +- src/agents/models/codex_children.py | 56 ++++ tests/models/test_codex_children.py | 299 ++++++++++++++++++ tests/models/test_codex_mutable_tool_hooks.py | 10 +- 9 files changed, 594 insertions(+), 19 deletions(-) create mode 100644 native/codex/src/children.rs create mode 100644 src/agents/models/codex_children.py create mode 100644 tests/models/test_codex_children.py diff --git a/native/codex/Cargo.lock b/native/codex/Cargo.lock index 6ebf0faa55..9d66da04d8 100644 --- a/native/codex/Cargo.lock +++ b/native/codex/Cargo.lock @@ -8053,6 +8053,7 @@ dependencies = [ "codex-protocol", "codex-sandboxing", "codex-skills-extension", + "codex-thread-store", "codex-utils-rustls-provider", "codex-web-search-extension", "futures", diff --git a/native/codex/Cargo.toml b/native/codex/Cargo.toml index 6c1143c54b..565a63038a 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"] } @@ -36,6 +37,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-rustls-provider = { git = "https://github.com/openai/codex", rev = "6ff1e1ca3b30fc8b914720681fcf5fe62e95f856" } codex-web-search-extension = { git = "https://github.com/openai/codex", rev = "6ff1e1ca3b30fc8b914720681fcf5fe62e95f856" } codex-code-mode = { git = "https://github.com/openai/codex", rev = "6ff1e1ca3b30fc8b914720681fcf5fe62e95f856" } @@ -43,7 +45,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..6730097dd3 --- /dev/null +++ b/native/codex/src/children.rs @@ -0,0 +1,137 @@ +//! Restrict an ephemeral tree before Core registers its collaboration tools. +use codex_core::config::{AgentRoleConfig, Config}; +use codex_features::Feature; +use codex_protocol::config_types::WebSearchMode; +use codex_protocol::openai_models::{ConfigShellToolType, ModelsResponse}; +use codex_protocol::protocol::MultiAgentVersion; +use pyo3::FromPyObject; +use serde_json::json; +use tempfile::TempDir; + +use crate::NativeResult; + +#[derive(FromPyObject)] +pub struct Children { + roles: Vec, + max_children: 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 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_children + ), + 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.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_max_threads != Some(self.max_children) + || config.agent_max_depth != self.max_depth + || config.experimental_request_user_input_enabled + || config.update_plan_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) + } +} + +// 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. Only remove tool capabilities. +pub fn catalog(mut catalog: ModelsResponse, model: &str) -> NativeResult { + catalog.models.retain(|entry| entry.slug == model); + let [entry] = catalog.models.as_mut_slice() else { + return Err("Native children require an exact V1 catalog model.".into()); + }; + if entry.multi_agent_version != Some(MultiAgentVersion::V1) { + return Err("Native children require a V1 Responses catalog model.".into()); + } + 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) +} diff --git a/native/codex/src/config.rs b/native/codex/src/config.rs index ea77d44944..e76198b60c 100644 --- a/native/codex/src/config.rs +++ b/native/codex/src/config.rs @@ -32,6 +32,7 @@ use serde_json::{Value, json}; type Result = std::result::Result; pub struct CoreServices { + pub children: Option>, pub config: Config, pub manager: Arc, home: PathBuf, @@ -306,6 +307,8 @@ pub async fn build_services( helper_executable: PathBuf, overrides: Vec, api_key: Option, + children: Option>, + model: Option<&str>, ) -> Result { codex_utils_rustls_provider::ensure_rustls_crypto_provider(); let cwd = PathBuf::from(cwd) @@ -317,6 +320,9 @@ 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())?); + } // These are the provider's defaults, preceding caller overrides. overrides.splice( 0..0, @@ -416,6 +422,22 @@ 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 = model.ok_or("Select an explicit V1 catalog model for native children.")?; + 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)?, + codex_models_manager::ModelOrigin::ExplicitConfig, + )); + } let paths = ExecServerRuntimeOptions::from_optional_paths( config.codex_self_exe.clone(), config.codex_linux_sandbox_exe.clone(), @@ -434,7 +456,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())?; @@ -483,7 +509,7 @@ pub async fn build_services( let mut manager = ThreadManager::new( &config, auth.clone(), - build_models_manager(&config, auth.clone()), + models, CodexAppsToolsCache::default(), SessionSource::Exec, environments, @@ -493,7 +519,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, @@ -513,6 +543,7 @@ pub async fn build_services( .borrow() .source_generation; Ok(CoreServices { + children, config, manager, home, @@ -900,6 +931,12 @@ 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.as_deref() != attempt["model"].as_str() { + return Err("Codex policy changed the native child model.".into()); + } + } configure_tools( &mut config, sdk_sandbox, diff --git a/native/codex/src/lib.rs b/native/codex/src/lib.rs index f6082ddb38..0e5de4f366 100644 --- a/native/codex/src/lib.rs +++ b/native/codex/src/lib.rs @@ -1,4 +1,5 @@ //! Private, asynchronous Core bindings for the opt-in Codex model provider. +mod children; mod config; mod tool_hooks; @@ -41,6 +42,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, @@ -55,7 +57,9 @@ 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 task = runtime().spawn(async move { + let _role_files = role_files; // Each fresh root owns an independent local agent runtime. Fence that // exact tree before waiting, so native subagents cannot outlive an attempt. let shutdown = services.manager.request_agent_tree_shutdown(id).await; @@ -127,12 +131,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>>, } @@ -167,12 +172,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); @@ -180,6 +189,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()); } @@ -190,6 +200,7 @@ async fn start_thread( .map_err(|_| "Unable to start the Codex thread.".to_owned())?; Ok(Arc::new(ThreadLease { record: Arc::new(ThreadRecord { + role_files: std::sync::Mutex::new(role_files), model: created.session_configured.model, id: created.thread_id, thread: created.thread, @@ -215,12 +226,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["model"].as_str(), ) .await { @@ -231,17 +245,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| { @@ -311,12 +326,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)); @@ -327,6 +343,7 @@ impl Manager { helper: PathBuf::from(helper_executable), overrides: config_overrides, api_key, + children: children.map(Arc::new), }, closed.clone(), )); @@ -355,7 +372,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."))?; diff --git a/src/agents/models/codex.py b/src/agents/models/codex.py index ca13c586db..ace8cc8fbd 100644 --- a/src/agents/models/codex.py +++ b/src/agents/models/codex.py @@ -55,6 +55,7 @@ from ._codex_items import CodexCustomToolCallOutput, CodexFunctionToolCallOutput from ._codex_tool_hooks import CodexToolHooks from ._run_context import get_model_tool_hooks +from .codex_children import CodexChildren as CodexChildren, CodexRole as CodexRole from .interface import Model, ModelProvider, ModelTracing @@ -63,6 +64,17 @@ class CodexProvider(ModelProvider): Codex owns workspace tools and authentication; the Runner owns SDK function tools, handoffs, approvals, and conversation history. Each request uses an ephemeral thread. + + Pass `children=CodexChildren(roles=(role,), max_children=2)` to isolate + native delegation within each request. Select an exact V1 catalog model + with `get_model`. This profile disables workspace tools, Code Mode and + MCP servers. SDK tools, handoffs and native tool hooks 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. + + Without `children`, Core uses its ordinary settings, which can also enable + delegation. The SDK adds no roles or limits in that case. """ _supports_stored_response_id = False @@ -73,7 +85,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 @@ -97,8 +113,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 @@ -288,6 +307,9 @@ async def stream_response( for tool in tools ) 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("Native children cannot use SDK tools, handoffs, or tool hooks.") if sdk_sandbox: system_instructions = "\n\n".join( filter( diff --git a/src/agents/models/codex_children.py b/src/agents/models/codex_children.py new file mode 100644 index 0000000000..1b96a1e153 --- /dev/null +++ b/src/agents/models/codex_children.py @@ -0,0 +1,56 @@ +"""Declarations for an isolated tree of native Codex agents.""" + +import re +from dataclasses import dataclass, field + + +@dataclass(frozen=True) +class CodexRole: + """A specialist the native parent can select by name and description.""" + + 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 delegation within one ephemeral model request. + + Roles supplement Core's default, explorer and worker roles. The model chooses + whether to delegate. A non-leaf can spawn, message, wait for, close + and resume agents within this tree. Closed ephemeral threads have no + stored history for reopening or full-history forks. Descendants inherit + the parent's model and permissions. Roles supply instructions only. + max_children limits open child threads across the tree, excluding the root. + A completed child can still occupy a slot until closed. max_depth counts + generations below the root. Neither limit bounds total requests or cost. + """ + + roles: tuple[CodexRole, ...] + max_children: int + max_depth: int = 1 + + def __post_init__(self) -> None: + if ( + not isinstance(self.roles, tuple) + or not self.roles + or any(not isinstance(role, CodexRole) for role in self.roles) + ): + raise ValueError("Provide a nonempty 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_children, 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/tests/models/test_codex_children.py b/tests/models/test_codex_children.py new file mode 100644 index 0000000000..0f87abf1b1 --- /dev/null +++ b/tests/models/test_codex_children.py @@ -0,0 +1,299 @@ +import asyncio +import json +from threading import Event + +import pytest + +from agents import Agent, RunConfig, Runner, UserError, function_tool +from agents.models.codex import CodexChildren, CodexProvider, CodexRole + +from .test_codex_mutable_tool_hooks import codex_fixture, final_message + +pytest_plugins = ["tests.models.test_codex_mutable_tool_hooks"] + +ROLE = CodexRole("editor", "Edit the draft.", 'Return "edited".\nStay concise.') +PROFILE = CodexChildren(roles=(ROLE,), max_children=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") + + +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_children=1) + for limit in [0, -1, True, 1.5, 2**31]: + for field in ("max_depth", "max_children"): + kwargs = {"max_children": 1, field: limit} + with pytest.raises(ValueError, match="limits"): + CodexChildren(roles=(ROLE,), **kwargs) + + +@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.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.", + "supported_reasoning_levels": [], + "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"): + result = await asyncio.wait_for( + Runner.run( + Agent(name="manager", model=provider.get_model(model)), + 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 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( + "model,extra", + [ + ("v2", []), + ("unknown", []), + ("v1", ["agents.max_depth=2"]), + ("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, match="V1|conflict"): + await ask(provider, model) + assert not requests + finally: + await provider.aclose() + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +async def test_native_children_slots_and_depth(tmp_path, monkeypatch, model_endpoint, catalog): + port, requests, items = model_endpoint + provider = codex_fixture(tmp_path, port, monkeypatch, catalog, children=PROFILE) + release = Event() + + def step(request): + receipts = outputs(request) + if "LEAF" in json.dumps([i for i in request["input"] if i.get("role") == "user"]): + if not receipts: + assert release.wait(10) + return call("spawn_agent", "grand", message="GRAND") + return final_message() + if not receipts: + return [ + call("spawn_agent", tag, message="LEAF", agent_type=ROLE.name) + for tag in ("one", "two") + ] + if "wait" not in receipts: + release.set() + target = next(json.loads(v)["agent_id"] for v in receipts.values() if "agent_id" in v) + return call("wait_agent", "wait", targets=[target], timeout_ms=10000) + return final_message() + + items.extend([step] * 5) + try: + await ask(provider) + assert len(requests) == 5 + 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 any("limit" in parent[tag] for tag in ("one", "two")) + assert "done" in parent["wait"] + finally: + release.set() + 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, 'agents.ambient.description="ambient specialist"'], + children=PROFILE, + ) + child_id = "" + + def step(request): + nonlocal child_id + if "LEAF" in json.dumps([i for i in request["input"] if i.get("role") == "user"]): + return final_message() + receipts = outputs(request) + if not receipts: + return [ + call("spawn_agent", "switch", message="LEAF", model="v2"), + 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) + 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 "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_children=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 = json.dumps([i for i in request["input"] if i.get("role") == "user"]) + 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() + + items.extend([step] * 9) + root = asyncio.create_task(ask(provider)) + try: + assert await asyncio.to_thread(started.wait, 10) + await ask(provider, prompt="FOREIGN") + await root + receipts = [outputs(r) for r in requests] + assert any("not found" in r.get("foreign", "") for r in receipts) + assert sum("done" in r.get("wait", "") for r in receipts) == 2 + assert len(requests) == 9 + finally: + release.set() + root.cancel() + await asyncio.gather(root, return_exceptions=True) + await provider.aclose() diff --git a/tests/models/test_codex_mutable_tool_hooks.py b/tests/models/test_codex_mutable_tool_hooks.py index 686d15e510..fa29da2e31 100644 --- a/tests/models/test_codex_mutable_tool_hooks.py +++ b/tests/models/test_codex_mutable_tool_hooks.py @@ -47,14 +47,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 = ( @@ -90,7 +93,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" @@ -112,6 +115,7 @@ def codex_fixture(tmp_path, port, monkeypatch, extra=()): "model_providers.fixture.stream_max_retries=0", *extra, ], + **options, ) From 89c3a08e1285e8bfc9872832046211ca91a4a4f3 Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Sat, 21 Nov 2026 07:08:50 -0800 Subject: [PATCH 2/5] Limit delegation attempts across the native agent tree --- native/codex/Cargo.lock | 1 + native/codex/Cargo.toml | 1 + native/codex/src/children.rs | 102 ++++++++++++++- native/codex/src/config.rs | 7 + native/codex/src/lib.rs | 5 + src/agents/models/codex.py | 7 +- src/agents/models/codex_children.py | 20 ++- tests/models/test_codex_children.py | 191 ++++++++++++++++++++++++---- 8 files changed, 303 insertions(+), 31 deletions(-) diff --git a/native/codex/Cargo.lock b/native/codex/Cargo.lock index 9d66da04d8..6aee4aed18 100644 --- a/native/codex/Cargo.lock +++ b/native/codex/Cargo.lock @@ -8041,6 +8041,7 @@ dependencies = [ "codex-core", "codex-core-api", "codex-exec-server", + "codex-extension-api", "codex-features", "codex-guardian-v2", "codex-hooks", diff --git a/native/codex/Cargo.toml b/native/codex/Cargo.toml index 565a63038a..defdf02b33 100644 --- a/native/codex/Cargo.toml +++ b/native/codex/Cargo.toml @@ -28,6 +28,7 @@ codex-config = { git = "https://github.com/openai/codex", rev = "6ff1e1ca3b30fc8 codex-core = { git = "https://github.com/openai/codex", rev = "6ff1e1ca3b30fc8b914720681fcf5fe62e95f856" } codex-core-api = { git = "https://github.com/openai/codex", rev = "6ff1e1ca3b30fc8b914720681fcf5fe62e95f856" } codex-exec-server = { git = "https://github.com/openai/codex", rev = "6ff1e1ca3b30fc8b914720681fcf5fe62e95f856" } +codex-extension-api = { git = "https://github.com/openai/codex", rev = "6ff1e1ca3b30fc8b914720681fcf5fe62e95f856" } codex-features = { git = "https://github.com/openai/codex", rev = "6ff1e1ca3b30fc8b914720681fcf5fe62e95f856" } codex-http-client = { git = "https://github.com/openai/codex", rev = "6ff1e1ca3b30fc8b914720681fcf5fe62e95f856" } codex-hooks = { git = "https://github.com/openai/codex", rev = "6ff1e1ca3b30fc8b914720681fcf5fe62e95f856" } diff --git a/native/codex/src/children.rs b/native/codex/src/children.rs index 6730097dd3..c9e6fb6ede 100644 --- a/native/codex/src/children.rs +++ b/native/codex/src/children.rs @@ -1,11 +1,21 @@ //! 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; @@ -13,7 +23,7 @@ use crate::NativeResult; #[derive(FromPyObject)] pub struct Children { roles: Vec, - max_children: usize, + max_delegations: usize, max_depth: i32, } @@ -38,6 +48,13 @@ const DISABLED: &[Feature] = &[ ]; impl Children { + pub fn budget(&self) -> Arc { + Arc::new(Budget { + remaining: Arc::new(AtomicUsize::new(self.max_delegations)), + denial: Arc::default(), + }) + } + pub fn defaults(&self) -> Vec { let mut overrides = vec![ "agents.enabled=true".into(), @@ -45,7 +62,7 @@ impl Children { "features.multi_agent_v2={enabled=false,disable_native_tools=true}".into(), format!( "agents.max_concurrent_threads_per_session={}", - self.max_children + self.max_delegations ), format!("agents.max_depth={}", self.max_depth), "tools.update_plan.enabled=false".into(), @@ -75,7 +92,7 @@ impl Children { .any(|server| server.enabled) || !config.multi_agent_v2.disable_native_tools || config.agent_default_subagent_model.is_some() - || config.agent_max_threads != Some(self.max_children) + || config.agent_max_threads != Some(self.max_delegations) || config.agent_max_depth != self.max_depth || config.experimental_request_user_input_enabled || config.update_plan_enabled @@ -135,3 +152,82 @@ pub fn catalog(mut catalog: ModelsResponse, model: &str) -> NativeResult, + denial: Arc>, +} + +impl Budget { + pub fn denial(&self) -> Option<&'static str> { + self.denial.get().copied() + } + + fn deny(&self, message: &'static str) -> ModelResponseError { + let _ = self.denial.set(message); + ModelResponseError::InvalidRequest { + message: message.to_owned(), + } + } + + fn admit(&self, item: &ResponseItem) -> Result<(), ModelResponseError> { + use ResponseItem::*; + 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") => + { + return Ok(()); + } + Message { .. } + | AgentMessage { .. } + | Reasoning { .. } + | AdditionalTools { .. } + | FunctionCallOutput { .. } + | CustomToolCallOutput { .. } + | ToolSearchOutput { .. } + | Compaction { .. } + | ConfigurationUpdate { .. } + | CompactionTrigger { .. } + | ContextCompaction { .. } => return Ok(()), + _ => {} + } + self.remaining + .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |left| { + left.checked_sub(1) + }) + .map_err(|_| self.deny("Codex native delegation limit exceeded."))?; + // V1 handlers cannot accept custom payloads. Fail before routing alternate forms. + if !matches!(item, FunctionCall { .. }) { + return Err(self.deny("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 e76198b60c..a170a2e5ce 100644 --- a/native/codex/src/config.rs +++ b/native/codex/src/config.rs @@ -32,6 +32,7 @@ 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, @@ -473,6 +474,7 @@ pub async fn build_services( } else { "codex-code-mode-host" }); + let budget = children.as_ref().map(|profile| profile.budget()); let manager = Arc::new_cyclic(|weak| { let mut extensions = ExtensionRegistryBuilder::::new(); codex_guardian_v2::install(&mut extensions, auth.clone(), weak.clone()); @@ -506,6 +508,10 @@ 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(), @@ -543,6 +549,7 @@ pub async fn build_services( .borrow() .source_generation; Ok(CoreServices { + budget, children, config, manager, diff --git a/native/codex/src/lib.rs b/native/codex/src/lib.rs index 0e5de4f366..efca394f94 100644 --- a/native/codex/src/lib.rs +++ b/native/codex/src/lib.rs @@ -414,6 +414,11 @@ impl Thread { Ok(tool_hooks::registered(&self.lease.thread, server)) } + #[getter] + fn delegation_error(&self) -> Option<&'static str> { + self.lease.services.budget.as_ref()?.denial() + } + fn inject_items<'py>( &self, py: Python<'py>, diff --git a/src/agents/models/codex.py b/src/agents/models/codex.py index ace8cc8fbd..7cd1e52dc8 100644 --- a/src/agents/models/codex.py +++ b/src/agents/models/codex.py @@ -65,7 +65,7 @@ class CodexProvider(ModelProvider): Codex owns workspace tools and authentication; the Runner owns SDK function tools, handoffs, approvals, and conversation history. Each request uses an ephemeral thread. - Pass `children=CodexChildren(roles=(role,), max_children=2)` to isolate + Pass `children=CodexChildren(roles=(role,), max_delegations=2)` to isolate native delegation within each request. Select an exact V1 catalog model with `get_model`. This profile disables workspace tools, Code Mode and MCP servers. SDK tools, handoffs and native tool hooks are @@ -504,6 +504,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 RuntimeError(thread.delegation_error) raise RuntimeError("Codex model turn failed.") if kind == "token_count": info = message.get("info") @@ -729,6 +731,9 @@ async def interrupt_when_ready() -> None: # Keep the attempt failure primary when joined cleanup also fails. if failure is None: raise + # A parent can finish without waiting for a child that exceeded the limit. + if children is not None and thread.delegation_error: + raise RuntimeError(thread.delegation_error) if native_pending: if not interrupt_requested: raise RuntimeError("Codex finished with an incomplete native tool call.") diff --git a/src/agents/models/codex_children.py b/src/agents/models/codex_children.py index 1b96a1e153..db500ad7d3 100644 --- a/src/agents/models/codex_children.py +++ b/src/agents/models/codex_children.py @@ -33,13 +33,23 @@ class CodexChildren: and resume agents within this tree. Closed ephemeral threads have no stored history for reopening or full-history forks. Descendants inherit the parent's model and permissions. Roles supply instructions only. - max_children limits open child threads across the tree, excluding the root. - A completed child can still occupy a slot until closed. max_depth counts - generations below the root. Neither limit bounds total requests or cost. + max_delegations caps attempts to spawn, resume or send input across + the tree, including failed calls. Unknown functions also count. + Only namespaced V1 wait and close functions are exempt. Other call + forms are rejected. Closing a child does not restore the budget. + Exceeding it stops the calling thread. Even if the parent finishes + normally, the SDK raises RuntimeError after joining the tree. + Already admitted calls can still run. max_depth counts generations + below the root. + + Waiting, model continuations and transport retries can still incur + requests. Neither limit caps model requests or cost. For a hard + request budget, use Agent.as_tool with separate parent and child turn + limits and shared application admission before each send and retry. """ roles: tuple[CodexRole, ...] - max_children: int + max_delegations: int max_depth: int = 1 def __post_init__(self) -> None: @@ -51,6 +61,6 @@ def __post_init__(self) -> None: raise ValueError("Provide a nonempty 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_children, self.max_depth): + for value in (self.max_delegations, 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/tests/models/test_codex_children.py b/tests/models/test_codex_children.py index 0f87abf1b1..939edbab70 100644 --- a/tests/models/test_codex_children.py +++ b/tests/models/test_codex_children.py @@ -1,6 +1,6 @@ import asyncio import json -from threading import Event +from threading import Barrier, Event import pytest @@ -12,7 +12,7 @@ pytest_plugins = ["tests.models.test_codex_mutable_tool_hooks"] ROLE = CodexRole("editor", "Edit the draft.", 'Return "edited".\nStay concise.') -PROFILE = CodexChildren(roles=(ROLE,), max_children=1) +PROFILE = CodexChildren(roles=(ROLE,), max_delegations=1) @pytest.mark.parametrize("name", ["", " ", "default", "explorer", "worker", "a/b"]) @@ -25,10 +25,10 @@ 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_children=1) + CodexChildren(roles=(ROLE, ROLE), max_delegations=1) for limit in [0, -1, True, 1.5, 2**31]: - for field in ("max_depth", "max_children"): - kwargs = {"max_children": 1, field: limit} + for field in ("max_depth", "max_delegations"): + kwargs = {"max_delegations": 1, field: limit} with pytest.raises(ValueError, match="limits"): CodexChildren(roles=(ROLE,), **kwargs) @@ -110,6 +110,10 @@ def call(name, tag, **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"] @@ -146,26 +150,21 @@ async def test_unsupported_children_before_generation( @pytest.mark.asyncio @pytest.mark.allow_call_model_methods -async def test_native_children_slots_and_depth(tmp_path, monkeypatch, model_endpoint, catalog): +async def test_native_children_at_depth_limit(tmp_path, monkeypatch, model_endpoint, catalog): port, requests, items = model_endpoint - provider = codex_fixture(tmp_path, port, monkeypatch, catalog, children=PROFILE) - release = Event() + children = CodexChildren(roles=(ROLE,), max_delegations=2) + provider = codex_fixture(tmp_path, port, monkeypatch, catalog, children=children) def step(request): receipts = outputs(request) - if "LEAF" in json.dumps([i for i in request["input"] if i.get("role") == "user"]): + if "LEAF" in user_input(request): if not receipts: - assert release.wait(10) return call("spawn_agent", "grand", message="GRAND") return final_message() if not receipts: - return [ - call("spawn_agent", tag, message="LEAF", agent_type=ROLE.name) - for tag in ("one", "two") - ] + return call("spawn_agent", "spawn", message="LEAF", agent_type=ROLE.name) if "wait" not in receipts: - release.set() - target = next(json.loads(v)["agent_id"] for v in receipts.values() if "agent_id" in v) + target = json.loads(receipts["spawn"])["agent_id"] return call("wait_agent", "wait", targets=[target], timeout_ms=10000) return final_message() @@ -180,10 +179,8 @@ def step(request): assert all(i.get("type") != "additional_tools" for i in leaf["input"]) assert "unsupported" in outputs(leaf)["grand"].lower() parent = outputs(requests[-1]) - assert any("limit" in parent[tag] for tag in ("one", "two")) assert "done" in parent["wait"] finally: - release.set() await provider.aclose() @@ -198,13 +195,13 @@ async def test_child_native_fork_reopen_and_model_selection( port, monkeypatch, [*catalog, 'agents.ambient.description="ambient specialist"'], - children=PROFILE, + children=CodexChildren(roles=(ROLE,), max_delegations=5), ) child_id = "" def step(request): nonlocal child_id - if "LEAF" in json.dumps([i for i in request["input"] if i.get("role") == "user"]): + if "LEAF" in user_input(request): return final_message() receipts = outputs(request) if not receipts: @@ -250,14 +247,14 @@ 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_children=2, max_depth=2) + children = CodexChildren(roles=(ROLE,), max_delegations=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 = json.dumps([i for i in request["input"] if i.get("role") == "user"]) + prompt = user_input(request) receipts = outputs(request) if "FOREIGN" in prompt: if not receipts: @@ -297,3 +294,153 @@ def step(request): 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=PROFILE) + + 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(RuntimeError, match="delegation limit exceeded"): + await ask(provider) + 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(RuntimeError, match="delegation limit exceeded"): + await ask(provider) + 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_delegations=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(RuntimeError, match="delegation limit exceeded"): + await ask(provider) + 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"): + await ask(provider) + assert len(requests) == 1 + finally: + await provider.aclose() + + +@pytest.mark.asyncio +@pytest.mark.allow_call_model_methods +async def test_child_counts_each_item_in_one_response( + tmp_path, monkeypatch, model_endpoint, catalog +): + port, requests, items = model_endpoint + provider = codex_fixture(tmp_path, port, monkeypatch, catalog, children=PROFILE) + items.append( + [ + call("send_input", "same", message="missing target"), + call("spawn_agent", "same", message="LEAF"), + ] + ) + items.append(final_message()) + try: + with pytest.raises(RuntimeError, match="delegation limit exceeded"): + await ask(provider) + assert len(requests) == 1 + finally: + await provider.aclose() From 29aaa337590a9acdc657024e9880ee1a02ccc804 Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Sun, 22 Nov 2026 01:20:25 -0800 Subject: [PATCH 3/5] Bound native child wait and close attempts across the delegation tree --- native/codex/src/children.rs | 24 ++++++++----- native/codex/src/config.rs | 5 ++- src/agents/models/codex_children.py | 11 +++--- tests/models/test_codex_children.py | 52 +++++++++++++++++++++++++++++ 4 files changed, 77 insertions(+), 15 deletions(-) diff --git a/native/codex/src/children.rs b/native/codex/src/children.rs index c9e6fb6ede..99d44bc903 100644 --- a/native/codex/src/children.rs +++ b/native/codex/src/children.rs @@ -48,11 +48,16 @@ const DISABLED: &[Feature] = &[ ]; impl Children { - pub fn budget(&self) -> Arc { - Arc::new(Budget { + pub fn budget(&self) -> NativeResult> { + let wait_close = self + .max_delegations + .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_delegations)), denial: Arc::default(), - }) + })) } pub fn defaults(&self) -> Vec { @@ -156,6 +161,7 @@ pub fn catalog(mut catalog: ModelsResponse, model: &str) -> NativeResult, + wait_close: Arc, denial: Arc>, } @@ -173,7 +179,7 @@ impl Budget { fn admit(&self, item: &ResponseItem) -> Result<(), ModelResponseError> { use ResponseItem::*; - match item { + let (remaining, error) = match item { // Core routes V1 functions by namespace and name, never by arguments or ID. FunctionCall { namespace: Some(ns), @@ -182,7 +188,7 @@ impl Budget { } if ns == "multi_agent_v1" && matches!(name.as_str(), "wait_agent" | "close_agent") => { - return Ok(()); + (&self.wait_close, "Codex native wait/close limit exceeded.") } Message { .. } | AgentMessage { .. } @@ -195,13 +201,13 @@ impl Budget { | ConfigurationUpdate { .. } | CompactionTrigger { .. } | ContextCompaction { .. } => return Ok(()), - _ => {} - } - self.remaining + _ => (&self.remaining, "Codex native delegation limit exceeded."), + }; + remaining .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |left| { left.checked_sub(1) }) - .map_err(|_| self.deny("Codex native delegation limit exceeded."))?; + .map_err(|_| self.deny(error))?; // V1 handlers cannot accept custom payloads. Fail before routing alternate forms. if !matches!(item, FunctionCall { .. }) { return Err(self.deny("Unsupported native delegation call.")); diff --git a/native/codex/src/config.rs b/native/codex/src/config.rs index 069ea80d4d..7a4ab4337b 100644 --- a/native/codex/src/config.rs +++ b/native/codex/src/config.rs @@ -476,7 +476,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()); + 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()); diff --git a/src/agents/models/codex_children.py b/src/agents/models/codex_children.py index db500ad7d3..85bfcdd2b6 100644 --- a/src/agents/models/codex_children.py +++ b/src/agents/models/codex_children.py @@ -35,15 +35,16 @@ class CodexChildren: the parent's model and permissions. Roles supply instructions only. max_delegations caps attempts to spawn, resume or send input across the tree, including failed calls. Unknown functions also count. - Only namespaced V1 wait and close functions are exempt. Other call - forms are rejected. Closing a child does not restore the budget. - Exceeding it stops the calling thread. Even if the parent finishes - normally, the SDK raises RuntimeError after joining the tree. + Namespaced V1 wait and close calls share a separate tree-wide limit + of twice max_delegations. Repeated, failed and timed-out calls count. + Other call forms are rejected. Closing a child restores neither allowance. + Exceeding either limit stops the calling thread. Even if the parent + finishes normally, the SDK raises RuntimeError after joining the tree. Already admitted calls can still run. max_depth counts generations below the root. Waiting, model continuations and transport retries can still incur - requests. Neither limit caps model requests or cost. For a hard + requests. These limits do not cap model requests, tokens or cost. For a hard request budget, use Agent.as_tool with separate parent and child turn limits and shared application admission before each send and retry. """ diff --git a/tests/models/test_codex_children.py b/tests/models/test_codex_children.py index c91dd422f1..69e0e5a7cd 100644 --- a/tests/models/test_codex_children.py +++ b/tests/models/test_codex_children.py @@ -478,3 +478,55 @@ async def test_child_counts_each_item_in_one_response( 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(RuntimeError, match="wait/close limit exceeded"): + await ask(provider) + 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_delegations=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(RuntimeError, match="wait/close limit exceeded"): + await ask(provider) + assert len(requests) == 5 + assert "done" in outputs(requests[-1])["wait"] + finally: + await provider.aclose() From f61bccb093f4867bd1e59907baf0653bc4e627f8 Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Mon, 23 Nov 2026 22:00:36 -0800 Subject: [PATCH 4/5] Allow built-in child roles and reject known conflicts before a session claim --- native/codex/src/children.rs | 4 +- src/agents/memory/resumable_session.py | 6 +- src/agents/models/_run_context.py | 2 +- src/agents/models/codex.py | 44 +++++++- src/agents/models/codex_children.py | 13 +-- src/agents/run.py | 10 +- src/agents/run_internal/native_approvals.py | 4 +- tests/models/test_codex_children.py | 118 +++++++++++++++++++- 8 files changed, 181 insertions(+), 20 deletions(-) diff --git a/native/codex/src/children.rs b/native/codex/src/children.rs index 0b210a66d1..ca56b469ef 100644 --- a/native/codex/src/children.rs +++ b/native/codex/src/children.rs @@ -83,6 +83,9 @@ impl Children { } 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) @@ -100,7 +103,6 @@ impl Children { || config.agent_max_threads != Some(self.max_delegation_attempts) || config.agent_max_depth != self.max_depth || config.experimental_request_user_input_enabled - || config.update_plan_enabled || config.web_search_mode.value() != WebSearchMode::Disabled || config.notify.as_ref().is_some_and(|args| !args.is_empty()) { 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 dded9566a9..116e68bcc1 100644 --- a/src/agents/models/_run_context.py +++ b/src/agents/models/_run_context.py @@ -17,7 +17,7 @@ @dataclass(frozen=True) class ModelToolHooks: - restore_config: RunConfig | None = field(default=None, kw_only=True, repr=False) + 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 d3fcbe6b07..803d5a2e27 100644 --- a/src/agents/models/codex.py +++ b/src/agents/models/codex.py @@ -117,7 +117,7 @@ async def main(slug): 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, native tool hooks and saved + 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. @@ -279,6 +279,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( @@ -481,7 +521,7 @@ async def stream_response( 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("Native children cannot use SDK tools, handoffs, or tool hooks.") + raise UserError(_CHILD_TOOL_CONFLICT) if sdk_sandbox: system_instructions = "\n\n".join( filter( diff --git a/src/agents/models/codex_children.py b/src/agents/models/codex_children.py index f9f98de286..2574ef24bd 100644 --- a/src/agents/models/codex_children.py +++ b/src/agents/models/codex_children.py @@ -89,7 +89,8 @@ class CodexChildren: The SDK skips the model retry policy and never retries either refusal. - The SDK copies the roles into a tuple. They supply instructions and + 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 and permissions. Closed threads have no saved history for reopening or @@ -97,19 +98,17 @@ class CodexChildren: model requests, retries, tokens or cost. """ - roles: tuple[CodexRole, ...] | list[CodexRole] + 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 not self.roles - or any(not isinstance(role, CodexRole) for role in self.roles) + if not isinstance(self.roles, tuple) or any( + not isinstance(role, CodexRole) for role in self.roles ): - raise ValueError("Provide a nonempty list or tuple of CodexRole declarations.") + 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): diff --git a/src/agents/run.py b/src/agents/run.py index 4c3b7db3fc..cac812242d 100644 --- a/src/agents/run.py +++ b/src/agents/run.py @@ -777,7 +777,7 @@ async def _run_impl( context_wrapper, hooks, run_config.tool_execution, - restore_config=run_config, + run_config=run_config, ), run_config.tool_not_found_behavior, ) @@ -798,7 +798,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, ) @@ -3044,7 +3048,7 @@ async def run_loop() -> None: context_wrapper, hooks, run_config.tool_execution, - restore_config=run_config, + 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 6cbbd7e9db..110cb77cc2 100644 --- a/src/agents/run_internal/native_approvals.py +++ b/src/agents/run_internal/native_approvals.py @@ -86,8 +86,8 @@ 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.restore_config is not None - model = get_model(bindings.agent, bindings.restore_config) + assert bindings.run_config is not None + model = get_model(bindings.agent, bindings.run_config) if isinstance(model, _CodexModel): model._provider._check_workspace_approval() diff --git a/tests/models/test_codex_children.py b/tests/models/test_codex_children.py index 97f5e2d220..55e46a4253 100644 --- a/tests/models/test_codex_children.py +++ b/tests/models/test_codex_children.py @@ -10,8 +10,10 @@ AgentsException, ModelRetrySettings, ModelSettings, + ResumableSession, RunConfig, Runner, + ToolExecutionConfig, UserError, function_tool, ) @@ -34,12 +36,19 @@ def test_invalid_child_role(name): CodexRole(name, "description", "instructions") -@pytest.mark.parametrize("roles", [[], (), "editor", [None], [ROLE, ROLE]]) +@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", " ") @@ -52,6 +61,104 @@ def test_invalid_child_declarations(): 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(): @@ -199,6 +306,7 @@ def outputs(request): ("v2", []), ("unknown", []), ("v1", ["agents.max_depth=2"]), + ("v1", ["tools.update_plan.enabled=true"]), ("v1", ["features.shell_tool=true"]), ("v1", ["features.multi_agent_v2=true"]), ], @@ -212,7 +320,9 @@ async def test_unsupported_children_before_generation( try: with pytest.raises(RuntimeError) as exc: await ask(provider, model) - if extra: + 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) == ( @@ -406,7 +516,9 @@ def step(request): @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=PROFILE) + provider = codex_fixture( + tmp_path, port, monkeypatch, catalog, children=CodexChildren(max_delegation_attempts=1) + ) def step(request): prompt = user_input(request) From aebee6fda9242052ad3f5acfe7036cbbf265536e Mon Sep 17 00:00:00 2001 From: Mark Stuart Date: Tue, 24 Nov 2026 08:18:21 -0800 Subject: [PATCH 5/5] Require an explicit child profile for native Codex delegation --- native/codex/src/config.rs | 7 ++++ src/agents/models/codex.py | 10 ++--- tests/models/test_codex_children.py | 62 +++++++++++++++++++++++++++++ 3 files changed, 74 insertions(+), 5 deletions(-) diff --git a/native/codex/src/config.rs b/native/codex/src/config.rs index 2be2f77aae..02a2c8b28a 100644 --- a/native/codex/src/config.rs +++ b/native/codex/src/config.rs @@ -329,6 +329,11 @@ pub async fn build_services( 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( @@ -961,6 +966,8 @@ pub async fn prepare_config(services: &CoreServices, attempt: &Value) -> Result< 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, diff --git a/src/agents/models/codex.py b/src/agents/models/codex.py index 4f74143c6f..697c0f8f37 100644 --- a/src/agents/models/codex.py +++ b/src/agents/models/codex.py @@ -78,8 +78,11 @@ class CodexProvider(ModelProvider): Supply the same SDK tool hooks on both workers. The user reviews the prepared input. Output preparation runs after execution. - Without `children`, Core's defaults and local configuration govern delegation. - To bound native children, run `codex debug models` with a CLI that matches + 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: @@ -122,9 +125,6 @@ async def main(slug): 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. - - Without `children`, Core uses its ordinary settings, which can also enable - delegation. The SDK adds no roles or limits in that case. """ _supports_stored_response_id = False diff --git a/tests/models/test_codex_children.py b/tests/models/test_codex_children.py index 48a9e1abf3..d782eaa7ad 100644 --- a/tests/models/test_codex_children.py +++ b/tests/models/test_codex_children.py @@ -305,6 +305,68 @@ def outputs(request): } +@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(