diff --git a/pyproject.toml b/pyproject.toml index 697d2ab..b835f3d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -38,7 +38,7 @@ classifiers = [ "Programming Language :: Python :: 3.13", "Typing :: Typed", ] -dependencies = ["jsonschema>=4.18,<5"] +dependencies = ["jsonschema>=4.18,<5", "tomli>=2,<3; python_version < '3.11'"] [project.optional-dependencies] # Cautious upper bounds on the pre-1.0 vendor SDKs: they move fast and have shipped @@ -46,14 +46,14 @@ dependencies = ["jsonschema>=4.18,<5"] # already-installed users from a surprise vendor release. The sdk-evolution agent # raises these deliberately after verifying a new version. claude = ["claude-agent-sdk>=0.2.87,<0.3"] -# 0.1.0b3 floor: earlier betas pin a codex binary with no manylinux wheels, -# making the extra uninstallable on glibc Linux. -codex = ["openai-codex>=0.1.0b3,<0.155"] +# 0.157.1 is the tested SDK and CLI pair for native named profiles. Earlier +# bundled CLIs do not enforce every profile rule needed by restricted runtimes. +codex = ["openai-codex>=0.157.1,<0.158"] antigravity = ["google-antigravity>=0.1.2,<0.2"] all = [ "claude-agent-sdk>=0.2.87,<0.3", "google-antigravity>=0.1.2,<0.2", - "openai-codex>=0.1.0b3,<0.155", + "openai-codex>=0.157.1,<0.158", ] [project.urls] @@ -71,7 +71,8 @@ dev = [ "pytest-asyncio>=0.23", "pytest-cov>=5.0", "ruff>=0.8", - "tomli>=2; python_version < '3.11'", + # Mypy checks the public Python 3.10 branch on every CI interpreter. + "tomli>=2", "types-jsonschema>=4.18", ] diff --git a/src/agent_runtime_kit/_types.py b/src/agent_runtime_kit/_types.py index 7a55066..4dd8a53 100644 --- a/src/agent_runtime_kit/_types.py +++ b/src/agent_runtime_kit/_types.py @@ -284,6 +284,7 @@ class AgentCapabilities: network_control: bool = False tool_filters: bool = False mcp_server_env: bool = False + named_permission_profiles: bool = False @dataclass(frozen=True) @@ -308,9 +309,7 @@ class TaskSupportReport: def __post_init__(self) -> None: issues = _tuple_value(self.issues, "TaskSupportReport.issues") if not all(isinstance(issue, TaskSupportIssue) for issue in issues): - raise ValueError( - "TaskSupportReport.issues must contain only TaskSupportIssue values" - ) + raise ValueError("TaskSupportReport.issues must contain only TaskSupportIssue values") object.__setattr__(self, "kind", AgentRuntimeKind.coerce(self.kind)) object.__setattr__(self, "issues", issues) @@ -524,13 +523,8 @@ def from_availability( ReadinessStatus.NOT_READY: "not ready", ReadinessStatus.INDETERMINATE: "readiness could not be determined", } - normalized_status = _coerce_enum( - ReadinessStatus, status, "RuntimeReadiness.status" - ) - if ( - normalized_status is ReadinessStatus.READY_TO_ATTEMPT - and not availability.available - ): + normalized_status = _coerce_enum(ReadinessStatus, status, "RuntimeReadiness.status") + if normalized_status is ReadinessStatus.READY_TO_ATTEMPT and not availability.available: raise ValueError("an unavailable package cannot be ready to attempt") return cls( kind=availability.kind, @@ -583,6 +577,10 @@ class PermissionProfile: "read-only", ...) and are coerced to enum members at construction, so a literal that slips past type checking can never silently bypass the adapters' identity comparisons. Unknown values raise ``ValueError``. + + ``native_profile`` requests a provider-defined named profile where supported. + In that case, the provider profile replaces this portable filesystem preset; + callers must define and verify the provider profile separately. """ mode: PermissionMode = PermissionMode.DEFAULT @@ -590,6 +588,7 @@ class PermissionProfile: allowed_tools: tuple[str, ...] = () disallowed_tools: tuple[str, ...] = () network: bool | None = None + native_profile: str | None = None def __post_init__(self) -> None: if not isinstance(self.mode, PermissionMode): @@ -619,6 +618,17 @@ def __post_init__(self) -> None: ) if self.network is not None and not isinstance(self.network, bool): raise ValueError("PermissionProfile.network must be bool or None") + if self.native_profile is not None: + if ( + not isinstance(self.native_profile, str) + or not self.native_profile + or not self.native_profile.isascii() + or not self.native_profile[0].isalnum() + or not all( + character.isalnum() or character in "_-" for character in self.native_profile + ) + ): + raise ValueError("PermissionProfile.native_profile must be a named profile ID") @dataclass(frozen=True) diff --git a/src/agent_runtime_kit/adapters/codex.py b/src/agent_runtime_kit/adapters/codex.py index 5d0ffc3..75122c9 100644 --- a/src/agent_runtime_kit/adapters/codex.py +++ b/src/agent_runtime_kit/adapters/codex.py @@ -3,13 +3,21 @@ from __future__ import annotations import asyncio +import hashlib import logging import os +import sys from collections.abc import Mapping +from pathlib import Path from typing import Any +if sys.version_info >= (3, 11): + import tomllib +else: # pragma: no cover - Python 3.10 + import tomli as tomllib + from agent_runtime_kit._control import RuntimeTaskController -from agent_runtime_kit._errors import AgentRuntimeUnavailableError +from agent_runtime_kit._errors import AgentRuntimeUnavailableError, UnsupportedTaskInputError from agent_runtime_kit._types import ( AgentCapabilities, AgentResult, @@ -22,6 +30,7 @@ ReadinessStatus, RuntimeAvailability, RuntimeReadiness, + TaskSupportIssue, TaskSupportReport, ToolCallAudit, Usage, @@ -80,6 +89,7 @@ class CodexAgentRuntime: tool_audit=True, cancellation=True, reasoning_effort=True, + named_permission_profiles=True, ) def __init__( @@ -96,9 +106,7 @@ def __init__( reuse_process: bool = False, ) -> None: self._default_model = default_model - self._supported_models = validate_model_configuration( - default_model, supported_models - ) + self._supported_models = validate_model_configuration(default_model, supported_models) # Plugins are disabled by default so headless runs are deterministic and do # not pick up host-local Codex plugin configuration. Override to opt in. self._config_overrides = config_overrides @@ -115,6 +123,10 @@ def __init__( self._sdk_process_reuse_count = 0 self._codex_client_lock = asyncio.Lock() self._codex_run_lock = asyncio.Lock() + # A live app-server does not reload a changed named permission profile. + # Freeze each requested profile's loaded configuration for this runtime + # instance; a caller must create a new instance to authorize a new policy. + self._native_policy_fingerprints: dict[tuple[str, str, str], str] = {} self._task_controller = RuntimeTaskController(self.kind) self._cleanup_quarantine = VendorCleanupQuarantine() @@ -192,10 +204,120 @@ def validate_task(self, task: AgentTask) -> TaskSupportReport: selection=selection, supported_models=self._supported_models, ) + profile_issue = self._native_profile_issue(task) return TaskSupportReport( kind=self.kind, - issues=report.issues + ((issue,) if issue is not None else ()), + issues=report.issues + + ((issue,) if issue is not None else ()) + + ((profile_issue,) if profile_issue is not None else ()), + ) + + def _native_profile_issue(self, task: AgentTask) -> TaskSupportIssue | None: + if task.permissions.native_profile is None: + return None + for override in self._config_overrides: + try: + parsed = tomllib.loads(override) + except tomllib.TOMLDecodeError: + return TaskSupportIssue( + "permissions.native_profile", "cannot inspect a Codex configuration override" + ) + if _has_key(parsed, {"sandbox_mode", "sandbox_workspace_write", "default_permissions"}): + return TaskSupportIssue( + "permissions.native_profile", + "named profiles cannot be combined with legacy sandbox " + "or conflicting profile overrides", + ) + for config_path in self._native_config_paths(task): + if config_path.is_symlink(): + return TaskSupportIssue( + "permissions.native_profile", "Codex configuration is a symlink" + ) + if not config_path.exists(): + continue + try: + parsed = tomllib.loads(config_path.read_text(encoding="utf-8")) + except (OSError, tomllib.TOMLDecodeError): + return TaskSupportIssue( + "permissions.native_profile", "cannot inspect the Codex configuration" + ) + if _has_key(parsed, {"sandbox_mode", "sandbox_workspace_write"}): + return TaskSupportIssue( + "permissions.native_profile", + "loaded Codex configuration contains legacy sandbox settings", + ) + return None + + def _native_config_paths(self, task: AgentTask) -> tuple[Path, ...]: + codex_home = (self._env or {}).get("CODEX_HOME") or os.environ.get("CODEX_HOME") + paths = [ + Path(codex_home) / "config.toml" + if codex_home + else Path.home() / ".codex" / "config.toml", + Path("/etc/codex/config.toml"), + ] + current = ( + task.working_directory.resolve() + if task.working_directory is not None + else Path.cwd().resolve() + ) + for root in (current, *current.parents): + paths.append(root / ".codex" / "config.toml") + if (root / ".git").exists(): + break + return tuple(paths) + + def _native_policy_fingerprint(self, task: AgentTask) -> tuple[tuple[str, str, str], str]: + profile = task.permissions.native_profile + if profile is None: + raise AssertionError("native profile fingerprint requires a named profile") + paths = self._native_config_paths(task) + digest = hashlib.sha256() + cwd = str( + task.working_directory.resolve() if task.working_directory else Path.cwd().resolve() ) + # Codex appends a trust record for the current workspace on the first + # turn. It is harmless to the selected permissions only when no project + # config exists to become active as a consequence of that transition. + project_config_present = any(path.exists() or path.is_symlink() for path in paths[2:]) + for index, path in enumerate(paths): + digest.update(os.fsencode(path.absolute())) + digest.update(b"\0") + if path.is_symlink(): + raise UnsupportedTaskInputError( + self.kind, "permissions.native_profile", "Codex configuration is a symlink" + ) + try: + content = path.read_bytes() + except FileNotFoundError: + digest.update(b"missing\0") + except OSError as exc: + raise UnsupportedTaskInputError( + self.kind, "permissions.native_profile", "cannot read Codex configuration" + ) from exc + else: + if index == 0: + try: + parsed = tomllib.loads(content.decode("utf-8")) + except (UnicodeDecodeError, tomllib.TOMLDecodeError) as exc: + raise UnsupportedTaskInputError( + self.kind, + "permissions.native_profile", + "cannot inspect the Codex configuration", + ) from exc + if not project_config_present: + projects = parsed.get("projects") + if isinstance(projects, dict) and projects.get(cwd) == { + "trust_level": "trusted" + }: + del projects[cwd] + if not projects: + del parsed["projects"] + content = repr(_stable_toml(parsed)).encode("utf-8") + digest.update(len(content).to_bytes(8, "big")) + digest.update(content) + codex_home = (self._env or {}).get("CODEX_HOME") or os.environ.get("CODEX_HOME") or "" + return (profile, cwd, codex_home), digest.hexdigest() async def run(self, task: AgentTask) -> AgentResult: """Execute one deadline- and cancellation-controlled Codex task.""" @@ -331,26 +453,51 @@ async def _run_codex( approval_mode_cls: Any, ) -> AgentResult: cwd = str(task.working_directory) if task.working_directory else None + native_profile = task.permissions.native_profile + overrides = self._config_overrides + if native_profile is not None: + overrides = (*overrides, f'default_permissions="{native_profile}"') config_kwargs: dict[str, Any] = { "cwd": cwd, - "config_overrides": self._config_overrides, + "config_overrides": overrides, } if self._env is not None: config_kwargs["env"] = dict(self._env) # Tolerate vendor option drift like the Claude adapter: drop kwargs the # installed SDK no longer accepts (instead of crashing with TypeError) and # record them so the omission stays visible in AgentResult.metadata. - config_supported, dropped = filter_supported_kwargs(config_cls, config_kwargs) + config_supported, dropped = filter_supported_kwargs( + config_cls, + config_kwargs, + required=("config_overrides",) if native_profile is not None else (), + kind=self.kind, + ) process_reused = False if self._reuse_process: async with self._codex_run_lock: try: + policy_fingerprint = None + if native_profile is not None: + scope, policy_fingerprint = self._native_policy_fingerprint(task) + previous = self._native_policy_fingerprints.get(scope) + if previous is not None and previous != policy_fingerprint: + # An already running app-server can retain the old + # profile even after its config file narrows. Evict + # it and require explicit construction of a new + # runtime under the new policy. + raise UnsupportedTaskInputError( + self.kind, + "permissions.native_profile", + "loaded named profile changed during process reuse", + ) + self._native_policy_fingerprints[scope] = policy_fingerprint key = _codex_client_key( config_kwargs, model=model, permissions=task.permissions, sandbox_cls=sandbox_cls, approval_mode_cls=approval_mode_cls, + policy_fingerprint=policy_fingerprint, ) codex, process_reused = await self._persistent_codex_client( codex_cls, @@ -426,7 +573,7 @@ async def _invoke_codex( run_kwargs: dict[str, Any] = { "cwd": cwd, "approval_mode": _approval_mode(task.permissions.mode, approval_mode_cls), - "sandbox": _sandbox_mode(task.permissions.filesystem, sandbox_cls), + "sandbox": _task_sandbox(task.permissions, sandbox_cls), } if model is not None: run_kwargs["model"] = model @@ -503,7 +650,7 @@ async def _start_or_resume_thread( "cwd": cwd, "developer_instructions": task.system, "approval_mode": _approval_mode(task.permissions.mode, approval_mode_cls), - "sandbox": _sandbox_mode(task.permissions.filesystem, sandbox_cls), + "sandbox": _task_sandbox(task.permissions, sandbox_cls), } if model is not None: kwargs["model"] = model @@ -518,6 +665,7 @@ async def _start_or_resume_thread( ) return await codex.thread_start(**supported), dropped + def _translate_run_result( task: AgentTask, raw_result: Any, @@ -538,6 +686,8 @@ def _translate_run_result( } if model is not None: metadata["model"] = model + if task.permissions.native_profile is not None: + metadata["requested_native_permission_profile"] = task.permissions.native_profile if dropped_options: metadata["dropped_options"] = list(dropped_options) status = _status_value(field_value(raw_result, "status")) @@ -757,6 +907,30 @@ def _sandbox_mode(filesystem: FilesystemAccess, sandbox_cls: Any) -> Any: return getattr(sandbox_cls, name, name.replace("_", "-")) +def _task_sandbox(permissions: Any, sandbox_cls: Any) -> Any: + # A None SDK sandbox argument leaves the named profile selected by + # default_permissions in force. Any legacy override takes precedence. + if permissions.native_profile is not None: + return None + return _sandbox_mode(permissions.filesystem, sandbox_cls) + + +def _has_key(value: Any, names: set[str]) -> bool: + return isinstance(value, dict) and any( + key in names or _has_key(child, names) for key, child in value.items() + ) + + +def _stable_toml(value: Any) -> Any: + """Keep TOML value types distinct while hashing its parsed structure.""" + + if isinstance(value, dict): + return ("table", tuple((key, _stable_toml(child)) for key, child in sorted(value.items()))) + if isinstance(value, list): + return ("array", tuple(_stable_toml(child) for child in value)) + return (type(value).__name__, repr(value)) + + def _codex_client_key( config_kwargs: Mapping[str, Any], *, @@ -764,6 +938,7 @@ def _codex_client_key( permissions: Any, sandbox_cls: Any, approval_mode_cls: Any, + policy_fingerprint: str | None = None, ) -> tuple[Any, ...]: env = config_kwargs.get("env") env_items = ( @@ -787,8 +962,10 @@ def _codex_client_key( model, str(permissions.mode), str(permissions.filesystem), + str(permissions.native_profile), + policy_fingerprint, str(_approval_mode(permissions.mode, approval_mode_cls)), - str(_sandbox_mode(permissions.filesystem, sandbox_cls)), + str(_task_sandbox(permissions, sandbox_cls)), ) diff --git a/src/agent_runtime_kit/compatibility.py b/src/agent_runtime_kit/compatibility.py index 3ba55bf..3237234 100644 --- a/src/agent_runtime_kit/compatibility.py +++ b/src/agent_runtime_kit/compatibility.py @@ -73,10 +73,10 @@ def __post_init__(self) -> None: extra="codex", package="openai-codex", module="openai_codex", - version_specifier=">=0.1.0b3,<0.155", - tested_version="0.154.0", + version_specifier=">=0.157.1,<0.158", + tested_version="0.157.1", tested_runtime_dependencies=( - PackageVersion(package="openai-codex-cli-bin", version="0.154.0"), + PackageVersion(package="openai-codex-cli-bin", version="0.157.1"), ), ), RuntimeCompatibility( diff --git a/src/agent_runtime_kit/support.py b/src/agent_runtime_kit/support.py index 1070833..6b12288 100644 --- a/src/agent_runtime_kit/support.py +++ b/src/agent_runtime_kit/support.py @@ -46,13 +46,9 @@ def _validate_declared_task_support( ) ) if task.session_id is not None and not capabilities.session_resume: - issues.append( - TaskSupportIssue("session_id", "runtime does not support session resume") - ) + issues.append(TaskSupportIssue("session_id", "runtime does not support session resume")) if task.resume_from is not None and not capabilities.session_resume: - issues.append( - TaskSupportIssue("resume_from", "runtime does not support session resume") - ) + issues.append(TaskSupportIssue("resume_from", "runtime does not support session resume")) if task.output_schema is not None and not capabilities.structured_output: issues.append( TaskSupportIssue("output_schema", "runtime does not support structured output") @@ -68,9 +64,7 @@ def _validate_declared_task_support( ) break if task.budget_usd is not None and not capabilities.budget: - issues.append( - TaskSupportIssue("budget_usd", "runtime does not expose a cost budget") - ) + issues.append(TaskSupportIssue("budget_usd", "runtime does not expose a cost budget")) if task.reasoning_effort is not None and not capabilities.reasoning_effort: issues.append( TaskSupportIssue( @@ -94,6 +88,13 @@ def _validate_declared_task_support( "runtime does not expose network access control", ) ) + if task.permissions.native_profile is not None and not capabilities.named_permission_profiles: + issues.append( + TaskSupportIssue( + "permissions.native_profile", + "runtime does not support named permission profiles", + ) + ) if not capabilities.tool_filters: if task.permissions.allowed_tools: issues.append( diff --git a/tests/test_codex_adapter.py b/tests/test_codex_adapter.py index 87c51da..4ea39ea 100644 --- a/tests/test_codex_adapter.py +++ b/tests/test_codex_adapter.py @@ -555,6 +555,241 @@ async def test_codex_sandbox_mapping(filesystem: FilesystemAccess, expected: str assert FakeThread.last_run_kwargs["sandbox"] == expected +@pytest.mark.asyncio +async def test_codex_named_profile_uses_config_without_legacy_sandbox_override( + tmp_path, monkeypatch +) -> None: + monkeypatch.setenv("CODEX_HOME", str(tmp_path)) + (tmp_path / "config.toml").write_text( + 'default_permissions = "bounded"\n[permissions.bounded.network]\nenabled = false\n' + ) + runtime = make_runtime() + + result = await runtime.run( + AgentTask( + goal="x", + permissions=PermissionProfile( + mode=PermissionMode.STRICT, + filesystem=FilesystemAccess.WORKSPACE_WRITE, + native_profile="bounded", + ), + ) + ) + + assert runtime.capabilities.named_permission_profiles + assert FakeCodex.instances[0].config.config_overrides[-1] == ('default_permissions="bounded"') + assert FakeCodex.last_started_kwargs is not None + assert FakeCodex.last_started_kwargs["sandbox"] is None + assert FakeThread.last_run_kwargs is not None + assert FakeThread.last_run_kwargs["sandbox"] is None + assert FakeThread.last_run_kwargs["approval_mode"] == "deny_all" + assert result.metadata["requested_native_permission_profile"] == "bounded" + + +@pytest.mark.asyncio +async def test_codex_reused_process_rejects_changed_named_profile(tmp_path, monkeypatch) -> None: + monkeypatch.setenv("CODEX_HOME", str(tmp_path)) + config = tmp_path / "config.toml" + original = f'[permissions.bounded.filesystem]\n":root" = "deny"\n"{tmp_path}" = "write"\n' + config.write_text(original) + runtime = make_runtime(reuse_process=True) + task = AgentTask( + goal="x", + working_directory=tmp_path, + permissions=PermissionProfile(native_profile="bounded"), + ) + + first = await runtime.run(task) + # A real Codex first turn appends this exact trust record. It does not + # change effective permission layers when no project config exists. + config.write_text(original + f'\n[projects."{tmp_path}"]\ntrust_level = "trusted"\n') + same_policy = await runtime.run( + AgentTask( + goal="again", + session_id=first.session_id, + working_directory=tmp_path, + permissions=task.permissions, + ) + ) + assert same_policy.metadata["sdk_process_reused"] is True + assert len(FakeCodex.instances) == 1 + + config.write_text( + f'[permissions.bounded.filesystem]\n":root" = "deny"\n"{tmp_path}" = "read"\n' + f'\n[projects."{tmp_path}"]\ntrust_level = "trusted"\n' + ) + with pytest.raises(UnsupportedTaskInputError, match="profile changed"): + await runtime.run( + AgentTask( + goal="after narrowing", + session_id=first.session_id, + working_directory=tmp_path, + permissions=task.permissions, + ) + ) + assert len(FakeCodex.instances) == 1 + assert FakeCodex.instances[0].closed is True + + # A new instance explicitly constructed under the changed profile starts a + # fresh app-server. The real SDK control probe confirms that even resuming + # the old conversation in a fresh process honors the narrower rule. + new_runtime = make_runtime(reuse_process=True) + new_result = await new_runtime.run( + AgentTask( + goal="authorized under read-only", + session_id=first.session_id, + working_directory=tmp_path, + permissions=task.permissions, + ) + ) + assert new_result.metadata["sdk_process_reused"] is False + assert len(FakeCodex.instances) == 2 + await new_runtime.aclose() + + +@pytest.mark.asyncio +async def test_codex_reused_process_rejects_trust_activation_of_project_config( + tmp_path, monkeypatch +) -> None: + codex_home = tmp_path / "home" + codex_home.mkdir() + monkeypatch.setenv("CODEX_HOME", str(codex_home)) + workspace = tmp_path / "workspace" + workspace.mkdir() + (workspace / ".git").mkdir() + project = workspace / ".codex" / "config.toml" + project.parent.mkdir() + project.write_text("[features]\nnetwork_proxy = true\n") + config = codex_home / "config.toml" + config.write_text("[permissions.bounded.network]\nenabled = false\n") + runtime = make_runtime(reuse_process=True) + task = AgentTask( + goal="x", + working_directory=workspace, + permissions=PermissionProfile(native_profile="bounded"), + ) + first = await runtime.run(task) + config.write_text( + "[permissions.bounded.network]\nenabled = false\n" + f'\n[projects."{workspace}"]\ntrust_level = "trusted"\n' + ) + with pytest.raises(UnsupportedTaskInputError, match="profile changed"): + await runtime.run( + AgentTask( + goal="resume", + working_directory=workspace, + session_id=first.session_id, + permissions=task.permissions, + ) + ) + assert FakeCodex.instances[0].closed is True + assert len(FakeCodex.instances) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "legacy", + [ + 'sandbox_mode = "danger-full-access"', + "'sandbox_mode' = \"danger-full-access\"", + "[sandbox_workspace_write]\nnetwork_access = true", + '[profiles.local]\nsandbox_mode = "danger-full-access"', + ], +) +async def test_codex_named_profile_rejects_legacy_file_settings( + tmp_path, monkeypatch, legacy: str +) -> None: + monkeypatch.setenv("CODEX_HOME", str(tmp_path)) + (tmp_path / "config.toml").write_text(legacy + "\n") + runtime = make_runtime() + + with pytest.raises(UnsupportedTaskInputError, match="legacy sandbox"): + await runtime.run( + AgentTask(goal="x", permissions=PermissionProfile(native_profile="bounded")) + ) + assert not FakeCodex.instances + + +@pytest.mark.asyncio +async def test_codex_named_profile_rejects_legacy_override(tmp_path, monkeypatch) -> None: + monkeypatch.setenv("CODEX_HOME", str(tmp_path)) + runtime = CodexAgentRuntime( + codex_cls=FakeCodex, + config_cls=FakeCodexConfig, + sandbox_cls=FakeSandbox, + approval_mode_cls=FakeApprovalMode, + config_overrides=("'sandbox_mode'=\"danger-full-access\"",), + ) + + with pytest.raises(UnsupportedTaskInputError, match="legacy sandbox"): + await runtime.run( + AgentTask(goal="x", permissions=PermissionProfile(native_profile="bounded")) + ) + assert not FakeCodex.instances + + +@pytest.mark.asyncio +async def test_codex_named_profile_rejects_project_legacy_config(tmp_path, monkeypatch) -> None: + codex_home = tmp_path / "codex-home" + codex_home.mkdir() + monkeypatch.setenv("CODEX_HOME", str(codex_home)) + repo = tmp_path / "repo" + repo.mkdir() + (repo / ".git").mkdir() + project_config = repo / ".codex" / "config.toml" + project_config.parent.mkdir() + project_config.write_text("'sandbox_mode' = 'danger-full-access'\n") + runtime = make_runtime() + + with pytest.raises(UnsupportedTaskInputError, match="legacy sandbox"): + await runtime.run( + AgentTask( + goal="x", + working_directory=repo, + permissions=PermissionProfile(native_profile="bounded"), + ) + ) + assert not FakeCodex.instances + + +@pytest.mark.asyncio +async def test_codex_named_profile_rejects_inherited_cwd_legacy_config( + tmp_path, monkeypatch +) -> None: + codex_home = tmp_path / "codex-home" + codex_home.mkdir() + monkeypatch.setenv("CODEX_HOME", str(codex_home)) + repo = tmp_path / "repo" + repo.mkdir() + (repo / ".git").mkdir() + project_config = repo / ".codex" / "config.toml" + project_config.parent.mkdir() + project_config.write_text("'sandbox_mode' = 'danger-full-access'\n") + monkeypatch.chdir(repo) + runtime = make_runtime() + + with pytest.raises(UnsupportedTaskInputError, match="legacy sandbox"): + await runtime.run( + AgentTask(goal="x", permissions=PermissionProfile(native_profile="bounded")) + ) + assert not FakeCodex.instances + + +@pytest.mark.asyncio +async def test_codex_named_profile_parses_comments_without_false_conflict( + tmp_path, monkeypatch +) -> None: + monkeypatch.setenv("CODEX_HOME", str(tmp_path)) + (tmp_path / "config.toml").write_text( + '# sandbox_mode = "danger-full-access"\ninstructions = "sandbox_mode is a documented key"\n' + ) + runtime = make_runtime() + + await runtime.run(AgentTask(goal="x", permissions=PermissionProfile(native_profile="bounded"))) + assert FakeThread.last_run_kwargs is not None + assert FakeThread.last_run_kwargs["sandbox"] is None + + @pytest.mark.asyncio async def test_codex_prefers_typed_model_and_effort_fields() -> None: runtime = make_runtime() diff --git a/tests/test_core.py b/tests/test_core.py index 3e09dbc..6dd2d48 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -92,6 +92,9 @@ def test_permission_profile_rejects_unknown_literals() -> None: # The error teaches the valid vocabulary. assert "strict" in message and "permissive" in message + with pytest.raises(ValueError, match="native_profile"): + PermissionProfile(native_profile='bad"profile') + with pytest.raises(ValueError): PermissionProfile(filesystem="ro") # type: ignore[arg-type] @@ -279,9 +282,7 @@ def test_finish_reason_enum_compares_as_string() -> None: def test_agent_result_success_is_explicit_and_rounds_are_non_negative() -> None: assert AgentResult(output="ok").is_success is True assert AgentResult(output="", finish_reason="failed").is_success is False - assert ( - AgentResult(output="", finish_reason="failed", error="vendor failed").is_success is False - ) + assert AgentResult(output="", finish_reason="failed", error="vendor failed").is_success is False with pytest.raises(ValueError, match="rounds"): AgentResult(output="", rounds=-1) diff --git a/uv.lock b/uv.lock index a41ee38..388f26c 100644 --- a/uv.lock +++ b/uv.lock @@ -29,6 +29,7 @@ version = "0.5.2" source = { editable = "." } dependencies = [ { name = "jsonschema" }, + { name = "tomli", marker = "python_full_version < '3.11'" }, ] [package.optional-dependencies] @@ -57,7 +58,7 @@ dev = [ { name = "pytest-asyncio" }, { name = "pytest-cov" }, { name = "ruff" }, - { name = "tomli", marker = "python_full_version < '3.11'" }, + { name = "tomli" }, { name = "types-jsonschema" }, ] @@ -68,8 +69,9 @@ requires-dist = [ { name = "google-antigravity", marker = "extra == 'all'", specifier = ">=0.1.2,<0.2" }, { name = "google-antigravity", marker = "extra == 'antigravity'", specifier = ">=0.1.2,<0.2" }, { name = "jsonschema", specifier = ">=4.18,<5" }, - { name = "openai-codex", marker = "extra == 'all'", specifier = ">=0.1.0b3,<0.155" }, - { name = "openai-codex", marker = "extra == 'codex'", specifier = ">=0.1.0b3,<0.155" }, + { name = "openai-codex", marker = "extra == 'all'", specifier = ">=0.157.1,<0.158" }, + { name = "openai-codex", marker = "extra == 'codex'", specifier = ">=0.157.1,<0.158" }, + { name = "tomli", marker = "python_full_version < '3.11'", specifier = ">=2,<3" }, ] provides-extras = ["claude", "codex", "antigravity", "all"] @@ -83,7 +85,7 @@ dev = [ { name = "pytest-asyncio", specifier = ">=0.23" }, { name = "pytest-cov", specifier = ">=5.0" }, { name = "ruff", specifier = ">=0.8" }, - { name = "tomli", marker = "python_full_version < '3.11'", specifier = ">=2" }, + { name = "tomli", specifier = ">=2" }, { name = "types-jsonschema", specifier = ">=4.18" }, ] @@ -946,31 +948,31 @@ wheels = [ [[package]] name = "openai-codex" -version = "0.154.0" +version = "0.157.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "openai-codex-cli-bin" }, { name = "packaging" }, { name = "pydantic" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/01/98/525a9ecbc927cb71f716e53b5e6840986a2a7ad1dabe8766bcaab6e5c4c3/openai_codex-0.154.0.tar.gz", hash = "sha256:55a2675ab92ad3f900bc6572ab9d7da857d089da4e2008ce3fa8539154e1c2c3", size = 86801, upload-time = "2026-09-10T19:51:08.001Z" } +sdist = { url = "https://files.pythonhosted.org/packages/1e/b5/b50b061d575bd76fa616fcfb2b5e732bccf816d0429e68bd47636dc16511/openai_codex-0.157.1.tar.gz", hash = "sha256:7c371c3be7722ffe36b9e8d823c05e3339a86b2f13403cc08fc2eaccf658d480", size = 89397, upload-time = "2026-09-26T01:14:34.727Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a4/66/bdadb71a855aebc965f21b721239cf4a265aa7c78cfcd0ab87ae4a44b68e/openai_codex-0.154.0-py3-none-any.whl", hash = "sha256:b5f354e1280621d0f5e28313ecf6974d2a98bcf0b088dbe791dc6df5044d2214", size = 94949, upload-time = "2026-09-10T19:51:06.371Z" }, + { url = "https://files.pythonhosted.org/packages/cb/9e/8620c10d9d76d21920162e81fa2d1bee9fbf55a3e66a7d9ba6d1f95a11d4/openai_codex-0.157.1-py3-none-any.whl", hash = "sha256:73a5051f9d68ab0c3e350e217664c2e46bb5aa10bfb3232144688bf600d65fbc", size = 97538, upload-time = "2026-09-26T01:14:33.348Z" }, ] [[package]] name = "openai-codex-cli-bin" -version = "0.154.0" +version = "0.157.1" source = { registry = "https://pypi.org/simple" } wheels = [ - { url = "https://files.pythonhosted.org/packages/d9/c5/4bd3ca28d82d54a5aae89d7106a81062f66bc113e24aa684a03855603586/openai_codex_cli_bin-0.154.0-py3-none-macosx_10_9_x86_64.whl", hash = "sha256:ce74d702b77f0e18df24cc47f5f5c14d88ce84a5df59ea07c0169bc92d0a98e2", size = 122467910, upload-time = "2026-09-10T19:40:22.967Z" }, - { url = "https://files.pythonhosted.org/packages/96/56/ee6e0ae89813d68ca12c19ab4cb4ddce30281b6d3f4dc46370f03b493f58/openai_codex_cli_bin-0.154.0-py3-none-macosx_11_0_arm64.whl", hash = "sha256:4f32974a4379e58f5d2677c4d5097aeaeef7e249c04ca8d66b569503999ba53b", size = 112690061, upload-time = "2026-09-10T19:40:29.003Z" }, - { url = "https://files.pythonhosted.org/packages/ac/48/11169686bed9637bd2b05675e0c62309d46b45a85065c515deca3aa47e3a/openai_codex_cli_bin-0.154.0-py3-none-manylinux_2_17_aarch64.whl", hash = "sha256:18c1235f7a3ece9c20ed7b02cba5501e0aec0b4027fed4c3805a703d7d745493", size = 118446658, upload-time = "2026-09-10T19:40:35.269Z" }, - { url = "https://files.pythonhosted.org/packages/0a/31/6558f90be93a8aa090a84e3cb683ac9f2fd1ff7c56cfd1878adcf74a3b49/openai_codex_cli_bin-0.154.0-py3-none-manylinux_2_17_x86_64.whl", hash = "sha256:1c1812526b7b1cc497de30392ce018125b017e96010824b4ca598514f44ce5be", size = 127394645, upload-time = "2026-09-10T19:40:42.838Z" }, - { url = "https://files.pythonhosted.org/packages/ca/a3/d823ea1d0c3f627047768ae8d9ae961d7e525197bcd78973121818e95dac/openai_codex_cli_bin-0.154.0-py3-none-musllinux_1_1_aarch64.whl", hash = "sha256:e850d84a2945f90ceb7fd609468d08fd654a00323f351db6bb2b204b7813ca0c", size = 118446656, upload-time = "2026-09-10T19:40:52.023Z" }, - { url = "https://files.pythonhosted.org/packages/18/a8/744f5d2f5e96626a194482e1310346ded6a574ead2c7c287e36518d06095/openai_codex_cli_bin-0.154.0-py3-none-musllinux_1_1_x86_64.whl", hash = "sha256:88f330201b527ee0d740d14aaea336f71e2513ba087bc9429373dc01fcd09f0d", size = 127394643, upload-time = "2026-09-10T19:40:59.099Z" }, - { url = "https://files.pythonhosted.org/packages/a4/e9/6759b73fa101e64bf86363982d810745952057316efe376118678a68a88d/openai_codex_cli_bin-0.154.0-py3-none-win_amd64.whl", hash = "sha256:11ba8fbef6f3bafaed39b745a2b0b5648bf00c8d168e241b314d86000d577fcb", size = 137545885, upload-time = "2026-09-10T19:41:06.777Z" }, - { url = "https://files.pythonhosted.org/packages/de/e9/695a272bfdf151ddd17c837ca5b167dfb2d87996dda4aba537be779817ca/openai_codex_cli_bin-0.154.0-py3-none-win_arm64.whl", hash = "sha256:f043e8fe1323246583ee35bf3c4c021cc9bfd21d2715f12fb8a743c8ebf57667", size = 127145338, upload-time = "2026-09-10T19:41:14.947Z" }, + { url = "https://files.pythonhosted.org/packages/c6/29/bb2884a56b938d7dbb9b81a42dbc527522e9540db09ed65200c512de2405/openai_codex_cli_bin-0.157.1-py3-none-macosx_10_9_x86_64.whl", hash = "sha256:a140e29b3c88a559067c9ec5bf300477e7ecb0f8cb5f49ffbcc0f68608637476", size = 130992160, upload-time = "2026-09-26T01:12:11.55Z" }, + { url = "https://files.pythonhosted.org/packages/8a/d5/f706f04b14664414fa7051f340426eb0f74b1bf17006795c2d4d7776a2cb/openai_codex_cli_bin-0.157.1-py3-none-macosx_11_0_arm64.whl", hash = "sha256:55b5b7cdb257440e97de69ad780a3ebff5a0adf8eb89564a7d7fc400c548b2de", size = 120546939, upload-time = "2026-09-26T01:12:18.951Z" }, + { url = "https://files.pythonhosted.org/packages/b5/58/aacc67a9556ccebdfd36c0c3c3ee9dc1bd878fb8b82eab14c846662b37d3/openai_codex_cli_bin-0.157.1-py3-none-manylinux_2_17_aarch64.whl", hash = "sha256:f26f1cdec2869f9a53155f3909d5ef5d85d6f80d49b59758d00cdcc4941edf82", size = 128579765, upload-time = "2026-09-26T01:12:28.551Z" }, + { url = "https://files.pythonhosted.org/packages/8a/d6/64d2eab534be58817262edf5949755aa665a22fea1220ce7273d751525c3/openai_codex_cli_bin-0.157.1-py3-none-manylinux_2_17_x86_64.whl", hash = "sha256:277a13acf88c2cde0d1a4f39373db4b267286b862ef8cf19bc9e8cc688b3786d", size = 138002592, upload-time = "2026-09-26T01:12:40.25Z" }, + { url = "https://files.pythonhosted.org/packages/ca/a0/f76fe6b91724175ce49b4c4bf4ec82cf1c33ee4a63f3972a26ca70c4fc2f/openai_codex_cli_bin-0.157.1-py3-none-musllinux_1_1_aarch64.whl", hash = "sha256:dc76cb00530a409b28233878f5961e85fc6e46ad9dd45ef958ef2594b1585baf", size = 138205669, upload-time = "2026-09-26T01:12:52.416Z" }, + { url = "https://files.pythonhosted.org/packages/60/24/53e9e1059d43dfd3ef89818adc189ed8cc56d2f2d9da1191e3ba23505fd0/openai_codex_cli_bin-0.157.1-py3-none-musllinux_1_1_x86_64.whl", hash = "sha256:477b6282b9b69131789b35c9ac198c8f499c374ba47dd82b2f34bf6472a585f4", size = 147768263, upload-time = "2026-09-26T01:13:05.761Z" }, + { url = "https://files.pythonhosted.org/packages/87/ab/2f06bb9bc77844deabeb9ace248b2033fd6e5fb5f79d8107ee10b849f2db/openai_codex_cli_bin-0.157.1-py3-none-win_amd64.whl", hash = "sha256:a6d589dd74645d448581f984f3d2427100fe53fd4eb4ca47db6a9d09190ab276", size = 147788910, upload-time = "2026-09-26T01:13:16.44Z" }, + { url = "https://files.pythonhosted.org/packages/f2/4c/ee1395f212a71ad25891fda1d2e93e4a07b17ac5a7b1bf4ccefd7ab709f8/openai_codex_cli_bin-0.157.1-py3-none-win_arm64.whl", hash = "sha256:14c40374b516edc27dface20b0e0817d8d60ccd398204771efa68abd6a650ca3", size = 136804354, upload-time = "2026-09-26T01:13:27.303Z" }, ] [[package]]