From 2e5153cf4b31330a5180d3b9a0b2038e3ed79dfd Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Mon, 20 Jul 2026 12:11:25 -0700 Subject: [PATCH] Make sandbox settings environment-owned --- .../schema/json/ClientRequest.json | 391 +++++++++++++++++ .../codex_app_server_protocol.schemas.json | 167 ++++++++ .../codex_app_server_protocol.v2.schemas.json | 167 ++++++++ .../schema/json/v2/ThreadStartParams.json | 398 ++++++++++++++++++ .../schema/json/v2/TurnStartParams.json | 391 +++++++++++++++++ .../schema/typescript/WindowsSandboxLevel.ts | 5 + .../schema/typescript/index.ts | 1 + ...nmentManagedFileSystemPermissionsParams.ts | 6 + .../typescript/v2/TurnEnvironmentParams.ts | 8 +- .../TurnEnvironmentPermissionProfileParams.ts | 7 + .../v2/TurnEnvironmentSandboxParams.ts | 8 + .../schema/typescript/v2/index.ts | 3 + .../src/protocol/v2/tests.rs | 22 +- .../src/protocol/v2/turn.rs | 171 ++++++++ codex-rs/app-server/src/request_processors.rs | 10 + .../tests/common/test_app_server.rs | 9 + .../tests/suite/v2/environment_add.rs | 1 + .../app-server/tests/suite/v2/mcp_tool.rs | 1 + .../suite/v2/selected_capability_stack.rs | 3 + .../app-server/tests/suite/v2/thread_start.rs | 2 + .../app-server/tests/suite/v2/turn_start.rs | 3 + codex-rs/core/src/apply_patch.rs | 6 +- .../src/context/world_state/environment.rs | 89 +++- .../world_state/environment_render_tests.rs | 14 +- .../context/world_state/environment_tests.rs | 49 ++- .../core/src/context_manager/history_tests.rs | 1 + codex-rs/core/src/environment_selection.rs | 71 +++- codex-rs/core/src/guardian/prompt.rs | 2 +- codex-rs/core/src/guardian/tests.rs | 4 +- codex-rs/core/src/mcp_openai_file.rs | 3 +- codex-rs/core/src/mcp_tool_call_tests.rs | 2 +- codex-rs/core/src/session/mod.rs | 23 +- codex-rs/core/src/session/review.rs | 10 +- .../session/rollout_reconstruction_tests.rs | 8 + codex-rs/core/src/session/session.rs | 58 ++- codex-rs/core/src/session/tests.rs | 48 ++- .../core/src/session/tests/guardian_tests.rs | 6 +- codex-rs/core/src/session/turn_context.rs | 257 ++++++++--- codex-rs/core/src/tasks/user_shell.rs | 23 +- codex-rs/core/src/thread_manager_tests.rs | 1 + .../core/src/tools/handlers/apply_patch.rs | 32 +- .../src/tools/handlers/extension_tools.rs | 5 +- .../src/tools/handlers/multi_agents_tests.rs | 4 +- codex-rs/core/src/tools/handlers/shell.rs | 4 +- .../src/tools/handlers/shell/shell_command.rs | 24 +- .../core/src/tools/handlers/shell_tests.rs | 12 +- .../handlers/unified_exec/exec_command.rs | 13 +- .../core/src/tools/handlers/view_image.rs | 6 +- codex-rs/core/src/tools/network_approval.rs | 8 +- codex-rs/core/src/tools/orchestrator.rs | 29 +- codex-rs/core/src/tools/registry.rs | 6 +- .../core/src/tools/runtimes/apply_patch.rs | 4 +- codex-rs/core/src/tools/runtimes/shell.rs | 6 +- .../tools/runtimes/shell/unix_escalation.rs | 9 +- .../runtimes/shell/unix_escalation_tests.rs | 8 +- .../core/src/tools/runtimes/unified_exec.rs | 6 +- codex-rs/core/src/tools/sandboxing.rs | 5 +- codex-rs/core/src/tools/spec_plan.rs | 11 +- codex-rs/core/src/unified_exec/mod_tests.rs | 2 +- .../core/src/unified_exec/process_manager.rs | 17 +- codex-rs/core/tests/common/test_codex.rs | 3 + codex-rs/core/tests/suite/agents_md.rs | 2 + codex-rs/core/tests/suite/apply_patch_cli.rs | 1 + .../core/tests/suite/model_visible_layout.rs | 1 + .../tests/suite/multi_exec_server_sandbox.rs | 24 +- codex-rs/core/tests/suite/network_approval.rs | 1 + codex-rs/core/tests/suite/remote_env.rs | 10 + codex-rs/core/tests/suite/resume_warning.rs | 1 + codex-rs/core/tests/suite/view_image.rs | 1 + codex-rs/protocol/src/protocol.rs | 34 ++ codex-rs/rollout/src/recorder_tests.rs | 1 + codex-rs/state/src/extract.rs | 4 + codex-rs/thread-store/src/local/mod.rs | 1 + .../src/local/model_context_tests.rs | 1 + 74 files changed, 2494 insertions(+), 251 deletions(-) create mode 100644 codex-rs/app-server-protocol/schema/typescript/WindowsSandboxLevel.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/TurnEnvironmentManagedFileSystemPermissionsParams.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/TurnEnvironmentPermissionProfileParams.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/TurnEnvironmentSandboxParams.ts diff --git a/codex-rs/app-server-protocol/schema/json/ClientRequest.json b/codex-rs/app-server-protocol/schema/json/ClientRequest.json index 996f9ea93c..9125e99382 100644 --- a/codex-rs/app-server-protocol/schema/json/ClientRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ClientRequest.json @@ -5,6 +5,26 @@ "description": "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", "type": "string" }, + "ActivePermissionProfile": { + "properties": { + "extends": { + "default": null, + "description": "Parent profile identifier from the selected permissions profile's `extends` setting, when present.", + "type": [ + "string", + "null" + ] + }, + "id": { + "description": "Identifier from `default_permissions` or the implicit built-in default, such as `:workspace` or a user-defined `[permissions.]` profile.", + "type": "string" + } + }, + "required": [ + "id" + ], + "type": "object" + }, "AddCreditsNudgeCreditType": { "enum": [ "credits", @@ -1012,6 +1032,210 @@ ], "type": "object" }, + "FileSystemAccessMode": { + "enum": [ + "read", + "write", + "deny" + ], + "type": "string" + }, + "FileSystemPath": { + "oneOf": [ + { + "properties": { + "path": { + "$ref": "#/definitions/LegacyAppPathString" + }, + "type": { + "enum": [ + "path" + ], + "title": "PathFileSystemPathType", + "type": "string" + } + }, + "required": [ + "path", + "type" + ], + "title": "PathFileSystemPath", + "type": "object" + }, + { + "properties": { + "pattern": { + "type": "string" + }, + "type": { + "enum": [ + "glob_pattern" + ], + "title": "GlobPatternFileSystemPathType", + "type": "string" + } + }, + "required": [ + "pattern", + "type" + ], + "title": "GlobPatternFileSystemPath", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "special" + ], + "title": "SpecialFileSystemPathType", + "type": "string" + }, + "value": { + "$ref": "#/definitions/FileSystemSpecialPath" + } + }, + "required": [ + "type", + "value" + ], + "title": "SpecialFileSystemPath", + "type": "object" + } + ] + }, + "FileSystemSandboxEntry": { + "properties": { + "access": { + "$ref": "#/definitions/FileSystemAccessMode" + }, + "path": { + "$ref": "#/definitions/FileSystemPath" + } + }, + "required": [ + "access", + "path" + ], + "type": "object" + }, + "FileSystemSpecialPath": { + "oneOf": [ + { + "properties": { + "kind": { + "enum": [ + "root" + ], + "type": "string" + } + }, + "required": [ + "kind" + ], + "title": "RootFileSystemSpecialPath", + "type": "object" + }, + { + "properties": { + "kind": { + "enum": [ + "minimal" + ], + "type": "string" + } + }, + "required": [ + "kind" + ], + "title": "MinimalFileSystemSpecialPath", + "type": "object" + }, + { + "properties": { + "kind": { + "enum": [ + "project_roots" + ], + "type": "string" + }, + "subpath": { + "anyOf": [ + { + "$ref": "#/definitions/LegacyAppPathString" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "kind" + ], + "title": "KindFileSystemSpecialPath", + "type": "object" + }, + { + "properties": { + "kind": { + "enum": [ + "tmpdir" + ], + "type": "string" + } + }, + "required": [ + "kind" + ], + "title": "TmpdirFileSystemSpecialPath", + "type": "object" + }, + { + "properties": { + "kind": { + "enum": [ + "slash_tmp" + ], + "type": "string" + } + }, + "required": [ + "kind" + ], + "title": "SlashTmpFileSystemSpecialPath", + "type": "object" + }, + { + "properties": { + "kind": { + "enum": [ + "unknown" + ], + "type": "string" + }, + "path": { + "type": "string" + }, + "subpath": { + "anyOf": [ + { + "$ref": "#/definitions/LegacyAppPathString" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "kind", + "path" + ], + "type": "object" + } + ] + }, "FsCopyParams": { "description": "Copy a file or directory tree on the host filesystem.", "properties": { @@ -4620,6 +4844,57 @@ ], "type": "object" }, + "TurnEnvironmentManagedFileSystemPermissionsParams": { + "oneOf": [ + { + "properties": { + "entries": { + "items": { + "$ref": "#/definitions/FileSystemSandboxEntry" + }, + "type": "array" + }, + "glob_scan_max_depth": { + "format": "uint", + "minimum": 1.0, + "type": [ + "integer", + "null" + ] + }, + "type": { + "enum": [ + "restricted" + ], + "title": "RestrictedTurnEnvironmentManagedFileSystemPermissionsParamsType", + "type": "string" + } + }, + "required": [ + "entries", + "type" + ], + "title": "RestrictedTurnEnvironmentManagedFileSystemPermissionsParams", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "unrestricted" + ], + "title": "UnrestrictedTurnEnvironmentManagedFileSystemPermissionsParamsType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "UnrestrictedTurnEnvironmentManagedFileSystemPermissionsParams", + "type": "object" + } + ] + }, "TurnEnvironmentParams": { "properties": { "cwd": { @@ -4637,6 +4912,17 @@ "array", "null" ] + }, + "sandbox": { + "anyOf": [ + { + "$ref": "#/definitions/TurnEnvironmentSandboxParams" + }, + { + "type": "null" + } + ], + "description": "Sandbox settings for this environment. Omitted inherits the thread sandbox settings." } }, "required": [ @@ -4645,6 +4931,103 @@ ], "type": "object" }, + "TurnEnvironmentPermissionProfileParams": { + "oneOf": [ + { + "properties": { + "file_system": { + "$ref": "#/definitions/TurnEnvironmentManagedFileSystemPermissionsParams" + }, + "network": { + "$ref": "#/definitions/NetworkAccess" + }, + "type": { + "enum": [ + "managed" + ], + "title": "ManagedTurnEnvironmentPermissionProfileParamsType", + "type": "string" + } + }, + "required": [ + "file_system", + "network", + "type" + ], + "title": "ManagedTurnEnvironmentPermissionProfileParams", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "disabled" + ], + "title": "DisabledTurnEnvironmentPermissionProfileParamsType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "DisabledTurnEnvironmentPermissionProfileParams", + "type": "object" + }, + { + "properties": { + "network": { + "$ref": "#/definitions/NetworkAccess" + }, + "type": { + "enum": [ + "external" + ], + "title": "ExternalTurnEnvironmentPermissionProfileParamsType", + "type": "string" + } + }, + "required": [ + "network", + "type" + ], + "title": "ExternalTurnEnvironmentPermissionProfileParams", + "type": "object" + } + ] + }, + "TurnEnvironmentSandboxParams": { + "properties": { + "activePermissionProfile": { + "anyOf": [ + { + "$ref": "#/definitions/ActivePermissionProfile" + }, + { + "type": "null" + } + ] + }, + "permissionProfile": { + "$ref": "#/definitions/TurnEnvironmentPermissionProfileParams" + }, + "useLegacyLandlock": { + "default": false, + "type": "boolean" + }, + "windowsSandboxLevel": { + "$ref": "#/definitions/WindowsSandboxLevel" + }, + "windowsSandboxPrivateDesktop": { + "default": false, + "type": "boolean" + } + }, + "required": [ + "permissionProfile", + "windowsSandboxLevel" + ], + "type": "object" + }, "TurnInterruptParams": { "properties": { "threadId": { @@ -5010,6 +5393,14 @@ } ] }, + "WindowsSandboxLevel": { + "enum": [ + "disabled", + "restricted-token", + "elevated" + ], + "type": "string" + }, "WindowsSandboxSetupMode": { "enum": [ "elevated", diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index 7f5b7cf081..7dcc578742 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -20828,6 +20828,57 @@ "title": "TurnDiffUpdatedNotification", "type": "object" }, + "TurnEnvironmentManagedFileSystemPermissionsParams": { + "oneOf": [ + { + "properties": { + "entries": { + "items": { + "$ref": "#/definitions/v2/FileSystemSandboxEntry" + }, + "type": "array" + }, + "glob_scan_max_depth": { + "format": "uint", + "minimum": 1.0, + "type": [ + "integer", + "null" + ] + }, + "type": { + "enum": [ + "restricted" + ], + "title": "RestrictedTurnEnvironmentManagedFileSystemPermissionsParamsType", + "type": "string" + } + }, + "required": [ + "entries", + "type" + ], + "title": "RestrictedTurnEnvironmentManagedFileSystemPermissionsParams", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "unrestricted" + ], + "title": "UnrestrictedTurnEnvironmentManagedFileSystemPermissionsParamsType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "UnrestrictedTurnEnvironmentManagedFileSystemPermissionsParams", + "type": "object" + } + ] + }, "TurnEnvironmentParams": { "properties": { "cwd": { @@ -20845,6 +20896,17 @@ "array", "null" ] + }, + "sandbox": { + "anyOf": [ + { + "$ref": "#/definitions/v2/TurnEnvironmentSandboxParams" + }, + { + "type": "null" + } + ], + "description": "Sandbox settings for this environment. Omitted inherits the thread sandbox settings." } }, "required": [ @@ -20853,6 +20915,103 @@ ], "type": "object" }, + "TurnEnvironmentPermissionProfileParams": { + "oneOf": [ + { + "properties": { + "file_system": { + "$ref": "#/definitions/v2/TurnEnvironmentManagedFileSystemPermissionsParams" + }, + "network": { + "$ref": "#/definitions/v2/NetworkAccess" + }, + "type": { + "enum": [ + "managed" + ], + "title": "ManagedTurnEnvironmentPermissionProfileParamsType", + "type": "string" + } + }, + "required": [ + "file_system", + "network", + "type" + ], + "title": "ManagedTurnEnvironmentPermissionProfileParams", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "disabled" + ], + "title": "DisabledTurnEnvironmentPermissionProfileParamsType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "DisabledTurnEnvironmentPermissionProfileParams", + "type": "object" + }, + { + "properties": { + "network": { + "$ref": "#/definitions/v2/NetworkAccess" + }, + "type": { + "enum": [ + "external" + ], + "title": "ExternalTurnEnvironmentPermissionProfileParamsType", + "type": "string" + } + }, + "required": [ + "network", + "type" + ], + "title": "ExternalTurnEnvironmentPermissionProfileParams", + "type": "object" + } + ] + }, + "TurnEnvironmentSandboxParams": { + "properties": { + "activePermissionProfile": { + "anyOf": [ + { + "$ref": "#/definitions/v2/ActivePermissionProfile" + }, + { + "type": "null" + } + ] + }, + "permissionProfile": { + "$ref": "#/definitions/v2/TurnEnvironmentPermissionProfileParams" + }, + "useLegacyLandlock": { + "default": false, + "type": "boolean" + }, + "windowsSandboxLevel": { + "$ref": "#/definitions/v2/WindowsSandboxLevel" + }, + "windowsSandboxPrivateDesktop": { + "default": false, + "type": "boolean" + } + }, + "required": [ + "permissionProfile", + "windowsSandboxLevel" + ], + "type": "object" + }, "TurnError": { "properties": { "additionalDetails": { @@ -21620,6 +21779,14 @@ }, "type": "object" }, + "WindowsSandboxLevel": { + "enum": [ + "disabled", + "restricted-token", + "elevated" + ], + "type": "string" + }, "WindowsSandboxReadiness": { "enum": [ "ready", diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index 3d87934c5b..56d39dab8a 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -18607,6 +18607,57 @@ "title": "TurnDiffUpdatedNotification", "type": "object" }, + "TurnEnvironmentManagedFileSystemPermissionsParams": { + "oneOf": [ + { + "properties": { + "entries": { + "items": { + "$ref": "#/definitions/FileSystemSandboxEntry" + }, + "type": "array" + }, + "glob_scan_max_depth": { + "format": "uint", + "minimum": 1.0, + "type": [ + "integer", + "null" + ] + }, + "type": { + "enum": [ + "restricted" + ], + "title": "RestrictedTurnEnvironmentManagedFileSystemPermissionsParamsType", + "type": "string" + } + }, + "required": [ + "entries", + "type" + ], + "title": "RestrictedTurnEnvironmentManagedFileSystemPermissionsParams", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "unrestricted" + ], + "title": "UnrestrictedTurnEnvironmentManagedFileSystemPermissionsParamsType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "UnrestrictedTurnEnvironmentManagedFileSystemPermissionsParams", + "type": "object" + } + ] + }, "TurnEnvironmentParams": { "properties": { "cwd": { @@ -18624,6 +18675,17 @@ "array", "null" ] + }, + "sandbox": { + "anyOf": [ + { + "$ref": "#/definitions/TurnEnvironmentSandboxParams" + }, + { + "type": "null" + } + ], + "description": "Sandbox settings for this environment. Omitted inherits the thread sandbox settings." } }, "required": [ @@ -18632,6 +18694,103 @@ ], "type": "object" }, + "TurnEnvironmentPermissionProfileParams": { + "oneOf": [ + { + "properties": { + "file_system": { + "$ref": "#/definitions/TurnEnvironmentManagedFileSystemPermissionsParams" + }, + "network": { + "$ref": "#/definitions/NetworkAccess" + }, + "type": { + "enum": [ + "managed" + ], + "title": "ManagedTurnEnvironmentPermissionProfileParamsType", + "type": "string" + } + }, + "required": [ + "file_system", + "network", + "type" + ], + "title": "ManagedTurnEnvironmentPermissionProfileParams", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "disabled" + ], + "title": "DisabledTurnEnvironmentPermissionProfileParamsType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "DisabledTurnEnvironmentPermissionProfileParams", + "type": "object" + }, + { + "properties": { + "network": { + "$ref": "#/definitions/NetworkAccess" + }, + "type": { + "enum": [ + "external" + ], + "title": "ExternalTurnEnvironmentPermissionProfileParamsType", + "type": "string" + } + }, + "required": [ + "network", + "type" + ], + "title": "ExternalTurnEnvironmentPermissionProfileParams", + "type": "object" + } + ] + }, + "TurnEnvironmentSandboxParams": { + "properties": { + "activePermissionProfile": { + "anyOf": [ + { + "$ref": "#/definitions/ActivePermissionProfile" + }, + { + "type": "null" + } + ] + }, + "permissionProfile": { + "$ref": "#/definitions/TurnEnvironmentPermissionProfileParams" + }, + "useLegacyLandlock": { + "default": false, + "type": "boolean" + }, + "windowsSandboxLevel": { + "$ref": "#/definitions/WindowsSandboxLevel" + }, + "windowsSandboxPrivateDesktop": { + "default": false, + "type": "boolean" + } + }, + "required": [ + "permissionProfile", + "windowsSandboxLevel" + ], + "type": "object" + }, "TurnError": { "properties": { "additionalDetails": { @@ -19399,6 +19558,14 @@ }, "type": "object" }, + "WindowsSandboxLevel": { + "enum": [ + "disabled", + "restricted-token", + "elevated" + ], + "type": "string" + }, "WindowsSandboxReadiness": { "enum": [ "ready", diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartParams.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartParams.json index 8bf5ae8bef..8c688e79e7 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartParams.json @@ -5,6 +5,26 @@ "description": "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", "type": "string" }, + "ActivePermissionProfile": { + "properties": { + "extends": { + "default": null, + "description": "Parent profile identifier from the selected permissions profile's `extends` setting, when present.", + "type": [ + "string", + "null" + ] + }, + "id": { + "description": "Identifier from `default_permissions` or the implicit built-in default, such as `:workspace` or a user-defined `[permissions.]` profile.", + "type": "string" + } + }, + "required": [ + "id" + ], + "type": "object" + }, "ApprovalsReviewer": { "description": "Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.", "enum": [ @@ -191,6 +211,210 @@ } ] }, + "FileSystemAccessMode": { + "enum": [ + "read", + "write", + "deny" + ], + "type": "string" + }, + "FileSystemPath": { + "oneOf": [ + { + "properties": { + "path": { + "$ref": "#/definitions/LegacyAppPathString" + }, + "type": { + "enum": [ + "path" + ], + "title": "PathFileSystemPathType", + "type": "string" + } + }, + "required": [ + "path", + "type" + ], + "title": "PathFileSystemPath", + "type": "object" + }, + { + "properties": { + "pattern": { + "type": "string" + }, + "type": { + "enum": [ + "glob_pattern" + ], + "title": "GlobPatternFileSystemPathType", + "type": "string" + } + }, + "required": [ + "pattern", + "type" + ], + "title": "GlobPatternFileSystemPath", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "special" + ], + "title": "SpecialFileSystemPathType", + "type": "string" + }, + "value": { + "$ref": "#/definitions/FileSystemSpecialPath" + } + }, + "required": [ + "type", + "value" + ], + "title": "SpecialFileSystemPath", + "type": "object" + } + ] + }, + "FileSystemSandboxEntry": { + "properties": { + "access": { + "$ref": "#/definitions/FileSystemAccessMode" + }, + "path": { + "$ref": "#/definitions/FileSystemPath" + } + }, + "required": [ + "access", + "path" + ], + "type": "object" + }, + "FileSystemSpecialPath": { + "oneOf": [ + { + "properties": { + "kind": { + "enum": [ + "root" + ], + "type": "string" + } + }, + "required": [ + "kind" + ], + "title": "RootFileSystemSpecialPath", + "type": "object" + }, + { + "properties": { + "kind": { + "enum": [ + "minimal" + ], + "type": "string" + } + }, + "required": [ + "kind" + ], + "title": "MinimalFileSystemSpecialPath", + "type": "object" + }, + { + "properties": { + "kind": { + "enum": [ + "project_roots" + ], + "type": "string" + }, + "subpath": { + "anyOf": [ + { + "$ref": "#/definitions/LegacyAppPathString" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "kind" + ], + "title": "KindFileSystemSpecialPath", + "type": "object" + }, + { + "properties": { + "kind": { + "enum": [ + "tmpdir" + ], + "type": "string" + } + }, + "required": [ + "kind" + ], + "title": "TmpdirFileSystemSpecialPath", + "type": "object" + }, + { + "properties": { + "kind": { + "enum": [ + "slash_tmp" + ], + "type": "string" + } + }, + "required": [ + "kind" + ], + "title": "SlashTmpFileSystemSpecialPath", + "type": "object" + }, + { + "properties": { + "kind": { + "enum": [ + "unknown" + ], + "type": "string" + }, + "path": { + "type": "string" + }, + "subpath": { + "anyOf": [ + { + "$ref": "#/definitions/LegacyAppPathString" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "kind", + "path" + ], + "type": "object" + } + ] + }, "LegacyAppPathString": { "type": "string" }, @@ -219,6 +443,13 @@ } ] }, + "NetworkAccess": { + "enum": [ + "restricted", + "enabled" + ], + "type": "string" + }, "Personality": { "enum": [ "none", @@ -274,6 +505,57 @@ ], "type": "string" }, + "TurnEnvironmentManagedFileSystemPermissionsParams": { + "oneOf": [ + { + "properties": { + "entries": { + "items": { + "$ref": "#/definitions/FileSystemSandboxEntry" + }, + "type": "array" + }, + "glob_scan_max_depth": { + "format": "uint", + "minimum": 1.0, + "type": [ + "integer", + "null" + ] + }, + "type": { + "enum": [ + "restricted" + ], + "title": "RestrictedTurnEnvironmentManagedFileSystemPermissionsParamsType", + "type": "string" + } + }, + "required": [ + "entries", + "type" + ], + "title": "RestrictedTurnEnvironmentManagedFileSystemPermissionsParams", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "unrestricted" + ], + "title": "UnrestrictedTurnEnvironmentManagedFileSystemPermissionsParamsType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "UnrestrictedTurnEnvironmentManagedFileSystemPermissionsParams", + "type": "object" + } + ] + }, "TurnEnvironmentParams": { "properties": { "cwd": { @@ -291,6 +573,17 @@ "array", "null" ] + }, + "sandbox": { + "anyOf": [ + { + "$ref": "#/definitions/TurnEnvironmentSandboxParams" + }, + { + "type": "null" + } + ], + "description": "Sandbox settings for this environment. Omitted inherits the thread sandbox settings." } }, "required": [ @@ -298,6 +591,111 @@ "environmentId" ], "type": "object" + }, + "TurnEnvironmentPermissionProfileParams": { + "oneOf": [ + { + "properties": { + "file_system": { + "$ref": "#/definitions/TurnEnvironmentManagedFileSystemPermissionsParams" + }, + "network": { + "$ref": "#/definitions/NetworkAccess" + }, + "type": { + "enum": [ + "managed" + ], + "title": "ManagedTurnEnvironmentPermissionProfileParamsType", + "type": "string" + } + }, + "required": [ + "file_system", + "network", + "type" + ], + "title": "ManagedTurnEnvironmentPermissionProfileParams", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "disabled" + ], + "title": "DisabledTurnEnvironmentPermissionProfileParamsType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "DisabledTurnEnvironmentPermissionProfileParams", + "type": "object" + }, + { + "properties": { + "network": { + "$ref": "#/definitions/NetworkAccess" + }, + "type": { + "enum": [ + "external" + ], + "title": "ExternalTurnEnvironmentPermissionProfileParamsType", + "type": "string" + } + }, + "required": [ + "network", + "type" + ], + "title": "ExternalTurnEnvironmentPermissionProfileParams", + "type": "object" + } + ] + }, + "TurnEnvironmentSandboxParams": { + "properties": { + "activePermissionProfile": { + "anyOf": [ + { + "$ref": "#/definitions/ActivePermissionProfile" + }, + { + "type": "null" + } + ] + }, + "permissionProfile": { + "$ref": "#/definitions/TurnEnvironmentPermissionProfileParams" + }, + "useLegacyLandlock": { + "default": false, + "type": "boolean" + }, + "windowsSandboxLevel": { + "$ref": "#/definitions/WindowsSandboxLevel" + }, + "windowsSandboxPrivateDesktop": { + "default": false, + "type": "boolean" + } + }, + "required": [ + "permissionProfile", + "windowsSandboxLevel" + ], + "type": "object" + }, + "WindowsSandboxLevel": { + "enum": [ + "disabled", + "restricted-token", + "elevated" + ], + "type": "string" } }, "properties": { diff --git a/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json b/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json index 477e57e43e..e929bb189a 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/TurnStartParams.json @@ -5,6 +5,26 @@ "description": "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", "type": "string" }, + "ActivePermissionProfile": { + "properties": { + "extends": { + "default": null, + "description": "Parent profile identifier from the selected permissions profile's `extends` setting, when present.", + "type": [ + "string", + "null" + ] + }, + "id": { + "description": "Identifier from `default_permissions` or the implicit built-in default, such as `:workspace` or a user-defined `[permissions.]` profile.", + "type": "string" + } + }, + "required": [ + "id" + ], + "type": "object" + }, "AdditionalContextEntry": { "properties": { "kind": { @@ -120,6 +140,210 @@ ], "type": "object" }, + "FileSystemAccessMode": { + "enum": [ + "read", + "write", + "deny" + ], + "type": "string" + }, + "FileSystemPath": { + "oneOf": [ + { + "properties": { + "path": { + "$ref": "#/definitions/LegacyAppPathString" + }, + "type": { + "enum": [ + "path" + ], + "title": "PathFileSystemPathType", + "type": "string" + } + }, + "required": [ + "path", + "type" + ], + "title": "PathFileSystemPath", + "type": "object" + }, + { + "properties": { + "pattern": { + "type": "string" + }, + "type": { + "enum": [ + "glob_pattern" + ], + "title": "GlobPatternFileSystemPathType", + "type": "string" + } + }, + "required": [ + "pattern", + "type" + ], + "title": "GlobPatternFileSystemPath", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "special" + ], + "title": "SpecialFileSystemPathType", + "type": "string" + }, + "value": { + "$ref": "#/definitions/FileSystemSpecialPath" + } + }, + "required": [ + "type", + "value" + ], + "title": "SpecialFileSystemPath", + "type": "object" + } + ] + }, + "FileSystemSandboxEntry": { + "properties": { + "access": { + "$ref": "#/definitions/FileSystemAccessMode" + }, + "path": { + "$ref": "#/definitions/FileSystemPath" + } + }, + "required": [ + "access", + "path" + ], + "type": "object" + }, + "FileSystemSpecialPath": { + "oneOf": [ + { + "properties": { + "kind": { + "enum": [ + "root" + ], + "type": "string" + } + }, + "required": [ + "kind" + ], + "title": "RootFileSystemSpecialPath", + "type": "object" + }, + { + "properties": { + "kind": { + "enum": [ + "minimal" + ], + "type": "string" + } + }, + "required": [ + "kind" + ], + "title": "MinimalFileSystemSpecialPath", + "type": "object" + }, + { + "properties": { + "kind": { + "enum": [ + "project_roots" + ], + "type": "string" + }, + "subpath": { + "anyOf": [ + { + "$ref": "#/definitions/LegacyAppPathString" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "kind" + ], + "title": "KindFileSystemSpecialPath", + "type": "object" + }, + { + "properties": { + "kind": { + "enum": [ + "tmpdir" + ], + "type": "string" + } + }, + "required": [ + "kind" + ], + "title": "TmpdirFileSystemSpecialPath", + "type": "object" + }, + { + "properties": { + "kind": { + "enum": [ + "slash_tmp" + ], + "type": "string" + } + }, + "required": [ + "kind" + ], + "title": "SlashTmpFileSystemSpecialPath", + "type": "object" + }, + { + "properties": { + "kind": { + "enum": [ + "unknown" + ], + "type": "string" + }, + "path": { + "type": "string" + }, + "subpath": { + "anyOf": [ + { + "$ref": "#/definitions/LegacyAppPathString" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "kind", + "path" + ], + "type": "object" + } + ] + }, "ImageDetail": { "enum": [ "auto", @@ -355,6 +579,57 @@ ], "type": "object" }, + "TurnEnvironmentManagedFileSystemPermissionsParams": { + "oneOf": [ + { + "properties": { + "entries": { + "items": { + "$ref": "#/definitions/FileSystemSandboxEntry" + }, + "type": "array" + }, + "glob_scan_max_depth": { + "format": "uint", + "minimum": 1.0, + "type": [ + "integer", + "null" + ] + }, + "type": { + "enum": [ + "restricted" + ], + "title": "RestrictedTurnEnvironmentManagedFileSystemPermissionsParamsType", + "type": "string" + } + }, + "required": [ + "entries", + "type" + ], + "title": "RestrictedTurnEnvironmentManagedFileSystemPermissionsParams", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "unrestricted" + ], + "title": "UnrestrictedTurnEnvironmentManagedFileSystemPermissionsParamsType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "UnrestrictedTurnEnvironmentManagedFileSystemPermissionsParams", + "type": "object" + } + ] + }, "TurnEnvironmentParams": { "properties": { "cwd": { @@ -372,6 +647,17 @@ "array", "null" ] + }, + "sandbox": { + "anyOf": [ + { + "$ref": "#/definitions/TurnEnvironmentSandboxParams" + }, + { + "type": "null" + } + ], + "description": "Sandbox settings for this environment. Omitted inherits the thread sandbox settings." } }, "required": [ @@ -380,6 +666,103 @@ ], "type": "object" }, + "TurnEnvironmentPermissionProfileParams": { + "oneOf": [ + { + "properties": { + "file_system": { + "$ref": "#/definitions/TurnEnvironmentManagedFileSystemPermissionsParams" + }, + "network": { + "$ref": "#/definitions/NetworkAccess" + }, + "type": { + "enum": [ + "managed" + ], + "title": "ManagedTurnEnvironmentPermissionProfileParamsType", + "type": "string" + } + }, + "required": [ + "file_system", + "network", + "type" + ], + "title": "ManagedTurnEnvironmentPermissionProfileParams", + "type": "object" + }, + { + "properties": { + "type": { + "enum": [ + "disabled" + ], + "title": "DisabledTurnEnvironmentPermissionProfileParamsType", + "type": "string" + } + }, + "required": [ + "type" + ], + "title": "DisabledTurnEnvironmentPermissionProfileParams", + "type": "object" + }, + { + "properties": { + "network": { + "$ref": "#/definitions/NetworkAccess" + }, + "type": { + "enum": [ + "external" + ], + "title": "ExternalTurnEnvironmentPermissionProfileParamsType", + "type": "string" + } + }, + "required": [ + "network", + "type" + ], + "title": "ExternalTurnEnvironmentPermissionProfileParams", + "type": "object" + } + ] + }, + "TurnEnvironmentSandboxParams": { + "properties": { + "activePermissionProfile": { + "anyOf": [ + { + "$ref": "#/definitions/ActivePermissionProfile" + }, + { + "type": "null" + } + ] + }, + "permissionProfile": { + "$ref": "#/definitions/TurnEnvironmentPermissionProfileParams" + }, + "useLegacyLandlock": { + "default": false, + "type": "boolean" + }, + "windowsSandboxLevel": { + "$ref": "#/definitions/WindowsSandboxLevel" + }, + "windowsSandboxPrivateDesktop": { + "default": false, + "type": "boolean" + } + }, + "required": [ + "permissionProfile", + "windowsSandboxLevel" + ], + "type": "object" + }, "UserInput": { "oneOf": [ { @@ -561,6 +944,14 @@ "type": "object" } ] + }, + "WindowsSandboxLevel": { + "enum": [ + "disabled", + "restricted-token", + "elevated" + ], + "type": "string" } }, "properties": { diff --git a/codex-rs/app-server-protocol/schema/typescript/WindowsSandboxLevel.ts b/codex-rs/app-server-protocol/schema/typescript/WindowsSandboxLevel.ts new file mode 100644 index 0000000000..5b4db76741 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/WindowsSandboxLevel.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type WindowsSandboxLevel = "disabled" | "restricted-token" | "elevated"; diff --git a/codex-rs/app-server-protocol/schema/typescript/index.ts b/codex-rs/app-server-protocol/schema/typescript/index.ts index e3e88adbf8..45bf3a2326 100644 --- a/codex-rs/app-server-protocol/schema/typescript/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/index.ts @@ -89,4 +89,5 @@ export type { WebSearchItem } from "./WebSearchItem"; export type { WebSearchLocation } from "./WebSearchLocation"; export type { WebSearchMode } from "./WebSearchMode"; export type { WebSearchToolConfig } from "./WebSearchToolConfig"; +export type { WindowsSandboxLevel } from "./WindowsSandboxLevel"; export * as v2 from "./v2"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/TurnEnvironmentManagedFileSystemPermissionsParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/TurnEnvironmentManagedFileSystemPermissionsParams.ts new file mode 100644 index 0000000000..5196a26f08 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/TurnEnvironmentManagedFileSystemPermissionsParams.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { FileSystemSandboxEntry } from "./FileSystemSandboxEntry"; + +export type TurnEnvironmentManagedFileSystemPermissionsParams = { "type": "restricted", entries: Array, glob_scan_max_depth?: number, } | { "type": "unrestricted" }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/TurnEnvironmentParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/TurnEnvironmentParams.ts index f51fcf33ee..e64319e8af 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/TurnEnvironmentParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/TurnEnvironmentParams.ts @@ -2,9 +2,15 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { LegacyAppPathString } from "../LegacyAppPathString"; +import type { TurnEnvironmentSandboxParams } from "./TurnEnvironmentSandboxParams"; export type TurnEnvironmentParams = { environmentId: string, cwd: LegacyAppPathString, /** * Environment-native runtime workspace roots. Omitted defaults to `cwd`. */ -runtimeWorkspaceRoots?: Array | null, }; +runtimeWorkspaceRoots?: Array | null, +/** + * Sandbox settings for this environment. Omitted inherits the thread + * sandbox settings. + */ +sandbox?: TurnEnvironmentSandboxParams | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/TurnEnvironmentPermissionProfileParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/TurnEnvironmentPermissionProfileParams.ts new file mode 100644 index 0000000000..5e4494f1fb --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/TurnEnvironmentPermissionProfileParams.ts @@ -0,0 +1,7 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { NetworkAccess } from "./NetworkAccess"; +import type { TurnEnvironmentManagedFileSystemPermissionsParams } from "./TurnEnvironmentManagedFileSystemPermissionsParams"; + +export type TurnEnvironmentPermissionProfileParams = { "type": "managed", file_system: TurnEnvironmentManagedFileSystemPermissionsParams, network: NetworkAccess, } | { "type": "disabled" } | { "type": "external", network: NetworkAccess, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/TurnEnvironmentSandboxParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/TurnEnvironmentSandboxParams.ts new file mode 100644 index 0000000000..3bba0fed9b --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/TurnEnvironmentSandboxParams.ts @@ -0,0 +1,8 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { WindowsSandboxLevel } from "../WindowsSandboxLevel"; +import type { ActivePermissionProfile } from "./ActivePermissionProfile"; +import type { TurnEnvironmentPermissionProfileParams } from "./TurnEnvironmentPermissionProfileParams"; + +export type TurnEnvironmentSandboxParams = { permissionProfile: TurnEnvironmentPermissionProfileParams, activePermissionProfile?: ActivePermissionProfile | null, windowsSandboxLevel: WindowsSandboxLevel, windowsSandboxPrivateDesktop: boolean, useLegacyLandlock: boolean, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts index f818e310ed..bb4a73c967 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts @@ -496,7 +496,10 @@ export type { ToolsV2 } from "./ToolsV2"; export type { Turn } from "./Turn"; export type { TurnCompletedNotification } from "./TurnCompletedNotification"; export type { TurnDiffUpdatedNotification } from "./TurnDiffUpdatedNotification"; +export type { TurnEnvironmentManagedFileSystemPermissionsParams } from "./TurnEnvironmentManagedFileSystemPermissionsParams"; export type { TurnEnvironmentParams } from "./TurnEnvironmentParams"; +export type { TurnEnvironmentPermissionProfileParams } from "./TurnEnvironmentPermissionProfileParams"; +export type { TurnEnvironmentSandboxParams } from "./TurnEnvironmentSandboxParams"; export type { TurnError } from "./TurnError"; export type { TurnInterruptParams } from "./TurnInterruptParams"; export type { TurnInterruptResponse } from "./TurnInterruptResponse"; diff --git a/codex-rs/app-server-protocol/src/protocol/v2/tests.rs b/codex-rs/app-server-protocol/src/protocol/v2/tests.rs index 22f96f159b..766ae3580e 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/tests.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/tests.rs @@ -4302,7 +4302,11 @@ fn turn_start_params_round_trip_environments() { { "environmentId": "local", "cwd": cwd, - "runtimeWorkspaceRoots": [workspace_root] + "runtimeWorkspaceRoots": [workspace_root], + "sandbox": { + "permissionProfile": {"type": "disabled"}, + "windowsSandboxLevel": "restricted-token" + } } ], })) @@ -4314,6 +4318,14 @@ fn turn_start_params_round_trip_environments() { environment_id: "local".to_string(), cwd: cwd.clone(), runtime_workspace_roots: Some(vec![workspace_root.clone()]), + sandbox: Some(TurnEnvironmentSandboxParams { + permission_profile: TurnEnvironmentPermissionProfileParams::Disabled, + active_permission_profile: None, + windows_sandbox_level: + codex_protocol::config_types::WindowsSandboxLevel::RestrictedToken, + windows_sandbox_private_desktop: false, + use_legacy_landlock: false, + }), }]) ); assert_eq!( @@ -4328,7 +4340,13 @@ fn turn_start_params_round_trip_environments() { { "environmentId": "local", "cwd": cwd, - "runtimeWorkspaceRoots": [workspace_root] + "runtimeWorkspaceRoots": [workspace_root], + "sandbox": { + "permissionProfile": {"type": "disabled"}, + "windowsSandboxLevel": "restricted-token", + "windowsSandboxPrivateDesktop": false, + "useLegacyLandlock": false + } } ])) ); diff --git a/codex-rs/app-server-protocol/src/protocol/v2/turn.rs b/codex-rs/app-server-protocol/src/protocol/v2/turn.rs index cb8473d49a..151f61f2de 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/turn.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/turn.rs @@ -1,5 +1,8 @@ +use super::ActivePermissionProfile; use super::ApprovalsReviewer; use super::AskForApproval; +use super::FileSystemSandboxEntry; +use super::NetworkAccess; use super::SandboxPolicy; use super::Turn; use codex_experimental_api_macros::ExperimentalApi; @@ -7,8 +10,12 @@ use codex_protocol::config_types::CollaborationMode; use codex_protocol::config_types::MultiAgentMode; use codex_protocol::config_types::Personality; use codex_protocol::config_types::ReasoningSummary; +use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::models::ImageDetail; +use codex_protocol::models::ManagedFileSystemPermissions as CoreManagedFileSystemPermissions; +use codex_protocol::models::PermissionProfile as CorePermissionProfile; use codex_protocol::openai_models::ReasoningEffort; +use codex_protocol::permissions::NetworkSandboxPolicy; use codex_protocol::plan_tool::PlanItemArg as CorePlanItemArg; use codex_protocol::plan_tool::StepStatus as CorePlanStepStatus; use codex_protocol::user_input::ByteRange as CoreByteRange; @@ -21,6 +28,8 @@ use serde::Deserialize; use serde::Serialize; use serde_json::Value as JsonValue; use std::collections::HashMap; +use std::io; +use std::num::NonZeroUsize; use std::path::PathBuf; use ts_rs::TS; @@ -44,6 +53,168 @@ pub struct TurnEnvironmentParams { /// Environment-native runtime workspace roots. Omitted defaults to `cwd`. #[ts(optional = nullable)] pub runtime_workspace_roots: Option>, + /// Sandbox settings for this environment. Omitted inherits the thread + /// sandbox settings. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional = nullable)] + pub sandbox: Option, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct TurnEnvironmentSandboxParams { + pub permission_profile: TurnEnvironmentPermissionProfileParams, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional = nullable)] + pub active_permission_profile: Option, + pub windows_sandbox_level: WindowsSandboxLevel, + #[serde(default)] + pub windows_sandbox_private_desktop: bool, + #[serde(default)] + pub use_legacy_landlock: bool, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(tag = "type", rename_all = "snake_case")] +#[ts(tag = "type", export_to = "v2/")] +pub enum TurnEnvironmentPermissionProfileParams { + #[serde(rename_all = "snake_case")] + #[ts(rename_all = "snake_case")] + Managed { + file_system: TurnEnvironmentManagedFileSystemPermissionsParams, + network: NetworkAccess, + }, + Disabled, + #[serde(rename_all = "snake_case")] + #[ts(rename_all = "snake_case")] + External { + network: NetworkAccess, + }, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(tag = "type", rename_all = "snake_case")] +#[ts(tag = "type", export_to = "v2/")] +pub enum TurnEnvironmentManagedFileSystemPermissionsParams { + #[serde(rename_all = "snake_case")] + #[ts(rename_all = "snake_case")] + Restricted { + entries: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + glob_scan_max_depth: Option, + }, + Unrestricted, +} + +impl TryFrom for codex_protocol::protocol::TurnEnvironmentSandbox { + type Error = io::Error; + + fn try_from(value: TurnEnvironmentSandboxParams) -> Result { + Ok(Self { + permission_profile: value.permission_profile.try_into()?, + active_permission_profile: value.active_permission_profile.map(Into::into), + windows_sandbox_level: value.windows_sandbox_level, + windows_sandbox_private_desktop: value.windows_sandbox_private_desktop, + use_legacy_landlock: value.use_legacy_landlock, + }) + } +} + +impl TryFrom for CorePermissionProfile { + type Error = io::Error; + + fn try_from(value: TurnEnvironmentPermissionProfileParams) -> Result { + Ok(match value { + TurnEnvironmentPermissionProfileParams::Managed { + file_system, + network, + } => Self::Managed { + file_system: file_system.try_into()?, + network: network.into(), + }, + TurnEnvironmentPermissionProfileParams::Disabled => Self::Disabled, + TurnEnvironmentPermissionProfileParams::External { network } => Self::External { + network: network.into(), + }, + }) + } +} + +impl From for TurnEnvironmentPermissionProfileParams { + fn from(value: CorePermissionProfile) -> Self { + match value { + CorePermissionProfile::Managed { + file_system, + network, + } => Self::Managed { + file_system: file_system.into(), + network: network.into(), + }, + CorePermissionProfile::Disabled => Self::Disabled, + CorePermissionProfile::External { network } => Self::External { + network: network.into(), + }, + } + } +} + +impl TryFrom + for CoreManagedFileSystemPermissions +{ + type Error = io::Error; + + fn try_from( + value: TurnEnvironmentManagedFileSystemPermissionsParams, + ) -> Result { + Ok(match value { + TurnEnvironmentManagedFileSystemPermissionsParams::Restricted { + entries, + glob_scan_max_depth, + } => Self::Restricted { + entries: entries + .into_iter() + .map(TryInto::try_into) + .collect::>>()?, + glob_scan_max_depth, + }, + TurnEnvironmentManagedFileSystemPermissionsParams::Unrestricted => Self::Unrestricted, + }) + } +} + +impl From for TurnEnvironmentManagedFileSystemPermissionsParams { + fn from(value: CoreManagedFileSystemPermissions) -> Self { + match value { + CoreManagedFileSystemPermissions::Restricted { + entries, + glob_scan_max_depth, + } => Self::Restricted { + entries: entries.into_iter().map(Into::into).collect(), + glob_scan_max_depth, + }, + CoreManagedFileSystemPermissions::Unrestricted => Self::Unrestricted, + } + } +} + +impl From for NetworkSandboxPolicy { + fn from(value: NetworkAccess) -> Self { + match value { + NetworkAccess::Restricted => Self::Restricted, + NetworkAccess::Enabled => Self::Enabled, + } + } +} + +impl From for NetworkAccess { + fn from(value: NetworkSandboxPolicy) -> Self { + match value { + NetworkSandboxPolicy::Restricted => Self::Restricted, + NetworkSandboxPolicy::Enabled => Self::Enabled, + } + } } #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] diff --git a/codex-rs/app-server/src/request_processors.rs b/codex-rs/app-server/src/request_processors.rs index a6d1794af0..ef9520be5d 100644 --- a/codex-rs/app-server/src/request_processors.rs +++ b/codex-rs/app-server/src/request_processors.rs @@ -591,6 +591,15 @@ fn resolve_turn_environment_selections( let mut selections = Vec::with_capacity(environments.len()); for environment in environments { let environment_id = environment.environment_id; + let sandbox = environment + .sandbox + .map(TryInto::try_into) + .transpose() + .map_err(|err| { + invalid_request(format!( + "invalid sandbox for environment `{environment_id}`: {err}" + )) + })?; let cwd = environment .cwd .to_inferred_path_uri() @@ -622,6 +631,7 @@ fn resolve_turn_environment_selections( environment_id, cwd, workspace_roots, + sandbox, }); } thread_manager diff --git a/codex-rs/app-server/tests/common/test_app_server.rs b/codex-rs/app-server/tests/common/test_app_server.rs index 26055f6aec..89fa966550 100644 --- a/codex-rs/app-server/tests/common/test_app_server.rs +++ b/codex-rs/app-server/tests/common/test_app_server.rs @@ -198,6 +198,15 @@ impl TestAppServer { environment_id: selection.environment_id.clone(), cwd: selection.cwd.clone().into(), runtime_workspace_roots: None, + sandbox: selection.sandbox.clone().map(|sandbox| { + codex_app_server_protocol::TurnEnvironmentSandboxParams { + permission_profile: sandbox.permission_profile.into(), + active_permission_profile: sandbox.active_permission_profile.map(Into::into), + windows_sandbox_level: sandbox.windows_sandbox_level, + windows_sandbox_private_desktop: sandbox.windows_sandbox_private_desktop, + use_legacy_landlock: sandbox.use_legacy_landlock, + } + }), }) } diff --git a/codex-rs/app-server/tests/suite/v2/environment_add.rs b/codex-rs/app-server/tests/suite/v2/environment_add.rs index 477c628132..79cfc126b7 100644 --- a/codex-rs/app-server/tests/suite/v2/environment_add.rs +++ b/codex-rs/app-server/tests/suite/v2/environment_add.rs @@ -101,6 +101,7 @@ async fn selected_environment_emits_connection_lifecycle_notifications() -> Resu cwd: codex_utils_absolute_path::AbsolutePathBuf::try_from(codex_home.path().to_path_buf())? .into(), runtime_workspace_roots: None, + sandbox: None, }; let request_id = app_server .send_thread_start_request(ThreadStartParams { diff --git a/codex-rs/app-server/tests/suite/v2/mcp_tool.rs b/codex-rs/app-server/tests/suite/v2/mcp_tool.rs index 453b4c0abf..56fc68d8a8 100644 --- a/codex-rs/app-server/tests/suite/v2/mcp_tool.rs +++ b/codex-rs/app-server/tests/suite/v2/mcp_tool.rs @@ -382,6 +382,7 @@ url = "{mcp_server_url}/mcp" )? .into(), runtime_workspace_roots: None, + sandbox: None, }]), selected_capability_roots: Some(vec![SelectedCapabilityRoot { id: "late-plugin@1".to_string(), diff --git a/codex-rs/app-server/tests/suite/v2/selected_capability_stack.rs b/codex-rs/app-server/tests/suite/v2/selected_capability_stack.rs index c104313a17..acfe694ebb 100644 --- a/codex-rs/app-server/tests/suite/v2/selected_capability_stack.rs +++ b/codex-rs/app-server/tests/suite/v2/selected_capability_stack.rs @@ -367,6 +367,7 @@ async fn selected_capabilities_become_available_between_samples_in_one_turn() -> environment_id: LOCAL_ENVIRONMENT_ID.to_string(), cwd: fixture.environment_cwd.into(), runtime_workspace_roots: None, + sandbox: None, }]), collaboration_mode: Some(CollaborationMode { mode: ModeKind::Plan, @@ -646,6 +647,7 @@ async fn start_thread( environment_id: LOCAL_ENVIRONMENT_ID.to_string(), cwd: environment_cwd.into(), runtime_workspace_roots: None, + sandbox: None, }]), selected_capability_roots: Some(vec![selected_root]), ..Default::default() @@ -677,6 +679,7 @@ async fn run_turn( environment_id: LOCAL_ENVIRONMENT_ID.to_string(), cwd: environment_cwd.into(), runtime_workspace_roots: None, + sandbox: None, }]), ..Default::default() }) diff --git a/codex-rs/app-server/tests/suite/v2/thread_start.rs b/codex-rs/app-server/tests/suite/v2/thread_start.rs index cf5cc13332..1eb187bec8 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_start.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_start.rs @@ -674,6 +674,7 @@ async fn thread_start_rejects_unknown_environment_as_invalid_request() -> Result environment_id: "missing".to_string(), cwd: workspace.into(), runtime_workspace_roots: None, + sandbox: None, }]), ..Default::default() }) @@ -712,6 +713,7 @@ async fn thread_start_rejects_relative_environment_cwd_as_invalid_request() -> R environment_id: environment_id.clone(), cwd: serde_json::from_value(json!("relative"))?, runtime_workspace_roots: None, + sandbox: None, }]), ..Default::default() }) diff --git a/codex-rs/app-server/tests/suite/v2/turn_start.rs b/codex-rs/app-server/tests/suite/v2/turn_start.rs index bbf92c37c0..6d898ef1fa 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_start.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_start.rs @@ -1478,6 +1478,7 @@ async fn turn_start_rejects_unknown_environment_before_starting_turn() -> Result )? .into(), runtime_workspace_roots: None, + sandbox: None, }]), ..Default::default() }) @@ -2649,6 +2650,7 @@ async fn turn_start_explicit_local_environment_updates_legacy_cwd_between_turns( environment_id: LOCAL_ENVIRONMENT_ID.to_string(), cwd: second_cwd.abs().into(), runtime_workspace_roots: None, + sandbox: None, }]), thread_id: thread.id.clone(), client_user_message_id: None, @@ -3033,6 +3035,7 @@ fn environment_params(ids: Option<&[&str]>, cwd: &Path) -> Option InternalApplyPatchInvocation { match assess_patch_safety( &action, turn_context.approval_policy.value(), - &turn_context.permission_profile(), + turn_environment.permission_profile(), file_system_sandbox_policy, &action.cwd, - turn_context.windows_sandbox_level, + turn_environment.settings.sandbox.windows_sandbox_level, ) { SafetyCheck::AutoApprove { user_explicitly_approved, diff --git a/codex-rs/core/src/context/world_state/environment.rs b/codex-rs/core/src/context/world_state/environment.rs index d5a8abf78d..aa5cd6270a 100644 --- a/codex-rs/core/src/context/world_state/environment.rs +++ b/codex-rs/core/src/context/world_state/environment.rs @@ -6,7 +6,6 @@ use crate::context::environment_context::NetworkContext; use crate::context::environment_context::push_xml_escaped_text; use crate::environment_selection::TurnEnvironmentSnapshot; use crate::session::turn_context::TurnContext; -use crate::session::turn_context::TurnEnvironment; use codex_utils_path_uri::PathUri; use serde::Deserialize; use serde::Serialize; @@ -19,7 +18,6 @@ pub(crate) struct EnvironmentsState { current_date: Option, timezone: Option, network: Option, - filesystem: Option, subagents: Option, } @@ -28,19 +26,11 @@ impl EnvironmentsState { turn_context: &TurnContext, environments: &TurnEnvironmentSnapshot, ) -> Self { - let workspace_roots = environments - .primary() - .map(TurnEnvironment::workspace_roots) - .unwrap_or_default(); Self { environments: environment_states(environments), current_date: turn_context.current_date.clone(), timezone: turn_context.timezone.clone(), network: network_from_turn_context(turn_context), - filesystem: Some(FileSystemContext::from_permission_profile( - turn_context.config.permissions.permission_profile(), - workspace_roots, - )), subagents: None, } } @@ -53,6 +43,7 @@ impl EnvironmentsState { } fn rendered_full(&self) -> RenderedEnvironments { + let legacy_single = is_legacy_single(&self.environments); RenderedEnvironments { updates: self .environments @@ -61,11 +52,18 @@ impl EnvironmentsState { (id.clone(), EnvironmentUpdate::Current(environment.clone())) }) .collect(), - legacy_single: is_legacy_single(&self.environments), + legacy_single, current_date: self.current_date.clone(), timezone: self.timezone.clone(), network: self.network.clone(), - filesystem: self.filesystem.clone(), + filesystem: legacy_single + .then(|| { + self.environments + .values() + .next() + .and_then(|environment| environment.filesystem.clone()) + }) + .flatten(), subagents: self.subagents.clone(), } } @@ -76,6 +74,7 @@ impl WorldStateSection for EnvironmentsState { type Snapshot = EnvironmentsSnapshot; fn snapshot(&self) -> Self::Snapshot { + let legacy_single = is_legacy_single(&self.environments); EnvironmentsSnapshot { environments: self .environments @@ -87,6 +86,14 @@ impl WorldStateSection for EnvironmentsState { cwd: environment.cwd.inferred_native_path_string(), status: environment.status, shell: environment.shell.clone(), + filesystem: (!legacy_single) + .then(|| { + environment + .filesystem + .as_ref() + .map(FileSystemContext::render) + }) + .flatten(), }, ) }) @@ -94,7 +101,16 @@ impl WorldStateSection for EnvironmentsState { current_date: self.current_date.clone(), timezone: self.timezone.clone(), network: self.network.as_ref().map(NetworkContext::render), - filesystem: self.filesystem.as_ref().map(FileSystemContext::render), + filesystem: legacy_single + .then(|| { + self.environments.values().next().and_then(|environment| { + environment + .filesystem + .as_ref() + .map(FileSystemContext::render) + }) + }) + .flatten(), subagents: self.subagents.clone(), } } @@ -143,7 +159,14 @@ impl WorldStateSection for EnvironmentsState { current_date: self.current_date.clone(), timezone: self.timezone.clone(), network: self.network.clone(), - filesystem: self.filesystem.clone(), + filesystem: legacy_single + .then(|| { + self.environments + .values() + .next() + .and_then(|environment| environment.filesystem.clone()) + }) + .flatten(), subagents: self.subagents.clone(), }) as Box }) @@ -200,7 +223,12 @@ impl ContextualUserFragment for RenderedEnvironments { let mut rendered = "\n".to_string(); if self.legacy_single { if let Some(EnvironmentUpdate::Current(environment)) = self.updates.values().next() { - push_environment_values(&mut rendered, environment, " "); + push_environment_values( + &mut rendered, + environment, + " ", + /*include_filesystem*/ false, + ); } } else if !self.updates.is_empty() { rendered.push_str(" \n"); @@ -211,7 +239,12 @@ impl ContextualUserFragment for RenderedEnvironments { push_xml_escaped_text(&mut rendered, id); rendered.push('"'); rendered.push_str(">\n"); - push_environment_values(&mut rendered, environment, " "); + push_environment_values( + &mut rendered, + environment, + " ", + /*include_filesystem*/ true, + ); rendered.push_str(" \n"); } EnvironmentUpdate::Unavailable => { @@ -248,7 +281,12 @@ impl ContextualUserFragment for RenderedEnvironments { } } -fn push_environment_values(rendered: &mut String, environment: &EnvironmentState, indent: &str) { +fn push_environment_values( + rendered: &mut String, + environment: &EnvironmentState, + indent: &str, + include_filesystem: bool, +) { rendered.push_str(indent); rendered.push_str(""); push_xml_escaped_text(rendered, &environment.cwd.inferred_native_path_string()); @@ -263,6 +301,11 @@ fn push_environment_values(rendered: &mut String, environment: &EnvironmentState push_xml_escaped_text(rendered, shell); rendered.push_str("\n"); } + if include_filesystem && let Some(filesystem) = &environment.filesystem { + rendered.push_str(indent); + rendered.push_str(&filesystem.render()); + rendered.push('\n'); + } } fn push_optional_element(rendered: &mut String, name: &str, value: Option<&str>) { @@ -283,6 +326,7 @@ struct EnvironmentState { cwd: PathUri, status: EnvironmentStatus, shell: Option, + filesystem: Option, } #[derive(Default, Deserialize, Serialize)] @@ -300,6 +344,8 @@ struct EnvironmentSnapshot { cwd: String, status: EnvironmentStatus, shell: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + filesystem: Option, } impl EnvironmentSnapshot { @@ -311,6 +357,7 @@ impl EnvironmentSnapshot { .as_ref() .zip(other.shell.as_ref()) .is_none_or(|(current, previous)| current == previous) + && self.filesystem == other.filesystem } } @@ -334,6 +381,10 @@ fn environment_states(snapshot: &TurnEnvironmentSnapshot) -> BTreeMap BTreeMap) -> (String, Env cwd, status: EnvironmentStatus::Available, shell: Some(shell.into()), + filesystem: None, }, ) } @@ -51,7 +52,6 @@ fn environment_state( current_date, timezone, network, - filesystem: None, subagents, } } @@ -97,7 +97,11 @@ fn serialize_environment_context_with_foreign_windows_cwd() { /*network*/ None, /*subagents*/ None, ); - context.filesystem = Some(FileSystemContext::from_permission_profile( + context + .environments + .get_mut("remote") + .expect("remote environment") + .filesystem = Some(FileSystemContext::from_permission_profile( &PermissionProfile::Disabled, &[PathUri::parse("file:///D:/workspace").expect("Windows workspace root URI")], )); @@ -191,7 +195,11 @@ fn serialize_environment_context_with_full_filesystem_profile() { /*network*/ None, /*subagents*/ None, ); - context.filesystem = Some(FileSystemContext::from_permission_profile( + context + .environments + .get_mut("local") + .expect("local environment") + .filesystem = Some(FileSystemContext::from_permission_profile( &workspace_write_permission_profile_with_private_denials(), &[ PathUri::from_abs_path(&repo), diff --git a/codex-rs/core/src/context/world_state/environment_tests.rs b/codex-rs/core/src/context/world_state/environment_tests.rs index 0e666ec64f..c1297719d3 100644 --- a/codex-rs/core/src/context/world_state/environment_tests.rs +++ b/codex-rs/core/src/context/world_state/environment_tests.rs @@ -56,47 +56,59 @@ fn snapshots() -> Result<()> { .collect(), ..Default::default() }; - let before_turn_context_changes = EnvironmentsState { + let mut before_turn_context_changes = EnvironmentsState { current_date: Some("2026-06-19".to_string()), timezone: Some("UTC".to_string()), network: Some(NetworkContext::new( vec!["old.example.com".to_string()], vec![], )), - filesystem: Some(FileSystemContext::from_permission_profile( - &PermissionProfile::Disabled, - &[], - )), ..environments.clone() }; - let after_turn_context_changes = EnvironmentsState { + before_turn_context_changes + .environments + .get_mut(LOCAL_ENVIRONMENT_ID) + .expect("local environment") + .filesystem = Some(FileSystemContext::from_permission_profile( + &PermissionProfile::Disabled, + &[], + )); + let mut after_turn_context_changes = EnvironmentsState { current_date: Some("2026-06-20".to_string()), timezone: Some("America/Los_Angeles".to_string()), network: Some(NetworkContext::new( vec!["new.example.com".to_string()], vec!["blocked.example.com".to_string()], )), - filesystem: Some(FileSystemContext::from_permission_profile( - &PermissionProfile::External { - network: NetworkSandboxPolicy::Restricted, - }, - &[], - )), ..environments }; - let foreign_windows = EnvironmentsState { + after_turn_context_changes + .environments + .get_mut(LOCAL_ENVIRONMENT_ID) + .expect("local environment") + .filesystem = Some(FileSystemContext::from_permission_profile( + &PermissionProfile::External { + network: NetworkSandboxPolicy::Restricted, + }, + &[], + )); + let mut foreign_windows = EnvironmentsState { environments: [( "remote".to_string(), available("file:///C:/windows", "powershell")?, )] .into_iter() .collect(), - filesystem: Some(FileSystemContext::from_permission_profile( - &PermissionProfile::Disabled, - &[], - )), ..Default::default() }; + foreign_windows + .environments + .get_mut("remote") + .expect("remote environment") + .filesystem = Some(FileSystemContext::from_permission_profile( + &PermissionProfile::Disabled, + &[], + )); let unknown_shell = EnvironmentsState { environments: [( LOCAL_ENVIRONMENT_ID.to_string(), @@ -104,6 +116,7 @@ fn snapshots() -> Result<()> { cwd: PathUri::parse("file:///repo")?, status: EnvironmentStatus::Available, shell: None, + filesystem: None, }, )] .into_iter() @@ -154,6 +167,7 @@ fn available(cwd: &str, shell: &str) -> Result { cwd: PathUri::parse(cwd)?, status: EnvironmentStatus::Available, shell: Some(shell.to_string()), + filesystem: None, }) } @@ -162,5 +176,6 @@ fn starting(cwd: &str) -> Result { cwd: PathUri::parse(cwd)?, status: EnvironmentStatus::Starting, shell: None, + filesystem: None, }) } diff --git a/codex-rs/core/src/context_manager/history_tests.rs b/codex-rs/core/src/context_manager/history_tests.rs index 027bdee1a7..f3038e79e6 100644 --- a/codex-rs/core/src/context_manager/history_tests.rs +++ b/codex-rs/core/src/context_manager/history_tests.rs @@ -255,6 +255,7 @@ fn reference_context_item() -> TurnContextItem { permission_profile: None, network: None, file_system_sandbox_policy: None, + environment_sandboxes: None, model: "gpt-test".to_string(), comp_hash: None, personality: None, diff --git a/codex-rs/core/src/environment_selection.rs b/codex-rs/core/src/environment_selection.rs index 97c9c0d3bd..e968aa207d 100644 --- a/codex-rs/core/src/environment_selection.rs +++ b/codex-rs/core/src/environment_selection.rs @@ -1,3 +1,4 @@ +use std::collections::BTreeMap; use std::collections::HashMap; use std::collections::HashSet; use std::fmt; @@ -14,6 +15,7 @@ use codex_exec_server::ExecutorFileSystem; use codex_protocol::protocol::EnvironmentConnectionEvent; use codex_protocol::protocol::Event; use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::TurnEnvironmentSandbox; use codex_protocol::protocol::TurnEnvironmentSelection; use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_path_uri::PathUri; @@ -23,6 +25,7 @@ use futures::future::Shared; use tokio_util::task::AbortOnDropHandle; use crate::session::turn_context::TurnEnvironment; +use crate::session::turn_context::TurnEnvironmentSettings; use crate::shell::Shell; use crate::shell_snapshot::ShellSnapshot; @@ -38,6 +41,7 @@ pub(crate) fn default_thread_environment_selections( environment_id, cwd: PathUri::from_abs_path(cwd), workspace_roots: workspace_roots.iter().map(PathUri::from_abs_path).collect(), + sandbox: None, }) .collect() } @@ -48,6 +52,7 @@ type TurnEnvironmentResolution = Shared, // Selection clones share one listener; the final handle drop aborts it. connection_events_task: Option>>, @@ -57,6 +62,7 @@ struct SelectedTurnEnvironment { #[derive(Clone)] pub(crate) struct StartingTurnEnvironment { pub(crate) selection: TurnEnvironmentSelection, + pub(crate) settings: TurnEnvironmentSettings, resolution: TurnEnvironmentResolution, } @@ -102,11 +108,13 @@ impl ThreadEnvironments { return None; }; let selection = environment.selection(); + let settings = environment.settings.clone(); let selected_environment = Arc::clone(&environment.environment); let resolution: TurnEnvironmentResolution = futures::future::ready(Ok(environment)).boxed().shared(); Some(SelectedTurnEnvironment { selection, + settings, environment: selected_environment, connection_events_task: None, resolution, @@ -123,7 +131,16 @@ impl ThreadEnvironments { } } + #[cfg(test)] pub(crate) fn update_selections(&self, environments: &[TurnEnvironmentSelection]) { + self.update_selections_with_settings(environments, &BTreeMap::new()); + } + + pub(crate) fn update_selections_with_settings( + &self, + environments: &[TurnEnvironmentSelection], + settings: &BTreeMap, + ) { let previous = self.environments.load(); let mut seen_environment_ids = HashSet::with_capacity(environments.len()); let mut next = Vec::with_capacity(environments.len()); @@ -131,10 +148,14 @@ impl ThreadEnvironments { if !seen_environment_ids.insert(selected_environment.environment_id.as_str()) { continue; } - if let Some(environment) = previous - .iter() - .find(|environment| environment.selection == *selected_environment) - && !matches!(environment.resolution.clone().now_or_never(), Some(Err(_))) + let environment_settings = settings + .get(&selected_environment.environment_id) + .cloned() + .unwrap_or_default(); + if let Some(environment) = previous.iter().find(|environment| { + environment.selection == *selected_environment + && environment.settings == environment_settings + }) && !matches!(environment.resolution.clone().now_or_never(), Some(Err(_))) { next.push(environment.clone()); continue; @@ -164,6 +185,7 @@ impl ThreadEnvironments { }); let (resolution_task, resolution) = Self::resolve_environment( selected_environment.clone(), + environment_settings.clone(), Arc::clone(&environment), self.local_shell.clone(), self.shell_snapshot.clone(), @@ -173,6 +195,7 @@ impl ThreadEnvironments { let resolution = resolution.boxed().shared(); next.push(SelectedTurnEnvironment { selection: selected_environment.clone(), + settings: environment_settings, environment, connection_events_task, resolution, @@ -263,6 +286,7 @@ impl ThreadEnvironments { fn resolve_environment( selection: TurnEnvironmentSelection, + settings: TurnEnvironmentSettings, environment: Arc, local_shell: Shell, shell_snapshot: ShellSnapshot, @@ -294,11 +318,13 @@ impl ThreadEnvironments { } else { Some(local_shell) }; - let mut turn_environment = TurnEnvironment::new( + let mut turn_environment = TurnEnvironment::new_with_settings( selection.environment_id, environment, selection.cwd, selection.workspace_roots, + selection.sandbox, + settings, shell, ); let task = shell_snapshot @@ -325,6 +351,7 @@ impl ThreadEnvironments { if let Some(environment) = TurnEnvironmentState::from_resolution( StartingTurnEnvironment { selection: environment.selection.clone(), + settings: environment.settings.clone(), resolution: environment.resolution.clone(), }, resolved, @@ -401,6 +428,24 @@ impl TurnEnvironmentSnapshot { }) } + pub(crate) fn environment_sandboxes(&self) -> BTreeMap { + self.turn_environments() + .filter_map(|environment| { + environment + .selection() + .sandbox + .map(|sandbox| (environment.environment_id.clone(), sandbox)) + }) + .chain(self.starting().filter_map(|environment| { + environment + .selection + .sandbox + .clone() + .map(|sandbox| (environment.selection.environment_id.clone(), sandbox)) + })) + .collect() + } + pub(crate) fn starting(&self) -> impl Iterator { self.environments.iter().filter_map(|environment| { let TurnEnvironmentState::Starting(environment) = environment else { @@ -591,6 +636,7 @@ mod tests { environment_id: REMOTE_ENVIRONMENT_ID.to_string(), cwd: cwd_uri.clone(), workspace_roots: vec![cwd_uri], + sandbox: None, }] ); } @@ -621,11 +667,13 @@ url = "ws://127.0.0.1:8765" environment_id: LOCAL_ENVIRONMENT_ID.to_string(), cwd: cwd_uri.clone(), workspace_roots: vec![cwd_uri.clone()], + sandbox: None, }, TurnEnvironmentSelection { environment_id: REMOTE_ENVIRONMENT_ID.to_string(), cwd: cwd_uri.clone(), workspace_roots: vec![cwd_uri], + sandbox: None, }, ] ); @@ -660,6 +708,7 @@ url = "ws://127.0.0.1:8765" environment_id: LOCAL_ENVIRONMENT_ID.to_string(), cwd: PathUri::from_abs_path(&cwd), workspace_roots: Vec::new(), + sandbox: None, }]); let snapshot = turn_environments.snapshot().await; @@ -681,6 +730,7 @@ url = "ws://127.0.0.1:8765" environment_id: LOCAL_ENVIRONMENT_ID.to_string(), cwd: cwd_uri.clone(), workspace_roots: Vec::new(), + sandbox: None, }; let resolved = resolve_turn_environments( @@ -691,6 +741,7 @@ url = "ws://127.0.0.1:8765" environment_id: LOCAL_ENVIRONMENT_ID.to_string(), cwd: cwd_uri.join("other").expect("other cwd URI"), workspace_roots: Vec::new(), + sandbox: None, }, ], ) @@ -712,6 +763,7 @@ url = "ws://127.0.0.1:8765" environment_id: "local".to_string(), cwd: selected_cwd_uri, workspace_roots: Vec::new(), + sandbox: None, }], ) .await; @@ -750,6 +802,7 @@ url = "ws://127.0.0.1:8765" environment_id: LOCAL_ENVIRONMENT_ID.to_string(), cwd: cwd_uri.clone(), workspace_roots: Vec::new(), + sandbox: None, }; let resolved = resolve_turn_environments( @@ -759,6 +812,7 @@ url = "ws://127.0.0.1:8765" environment_id: "missing".to_string(), cwd: cwd_uri, workspace_roots: Vec::new(), + sandbox: None, }, local.clone(), ], @@ -787,6 +841,7 @@ url = "ws://127.0.0.1:8765" environment_id: REMOTE_ENVIRONMENT_ID.to_string(), cwd: PathUri::from_abs_path(&AbsolutePathBuf::current_dir().expect("cwd")), workspace_roots: Vec::new(), + sandbox: None, }; let environments = Arc::new(ThreadEnvironments::new( manager, @@ -835,11 +890,13 @@ url = "ws://127.0.0.1:8765" environment_id: REMOTE_ENVIRONMENT_ID.to_string(), cwd: cwd.clone(), workspace_roots: Vec::new(), + sandbox: None, }; let local = TurnEnvironmentSelection { environment_id: LOCAL_ENVIRONMENT_ID.to_string(), cwd, workspace_roots: Vec::new(), + sandbox: None, }; let turn_environments = ThreadEnvironments::new( manager, @@ -914,6 +971,7 @@ url = "ws://127.0.0.1:8765" environment_id: REMOTE_ENVIRONMENT_ID.to_string(), cwd: PathUri::from_abs_path(&AbsolutePathBuf::current_dir().expect("cwd")), workspace_roots: Vec::new(), + sandbox: None, }; let environments = ThreadEnvironments::new( Arc::clone(&manager), @@ -967,6 +1025,7 @@ url = "ws://127.0.0.1:8765" environment_id: REMOTE_ENVIRONMENT_ID.to_string(), cwd: PathUri::from_abs_path(&cwd), workspace_roots: Vec::new(), + sandbox: None, }; let (tx_event, rx_event) = async_channel::unbounded(); let environments = Arc::new(ThreadEnvironments::new( @@ -1050,6 +1109,7 @@ url = "ws://127.0.0.1:8765" environment_id: REMOTE_ENVIRONMENT_ID.to_string(), cwd: PathUri::from_abs_path(&cwd), workspace_roots: Vec::new(), + sandbox: None, }; let inherited_environment = Arc::new( Environment::create_for_tests(Some("ws://127.0.0.1:8765".to_string())) @@ -1103,6 +1163,7 @@ url = "ws://127.0.0.1:8765" environment_id: LOCAL_ENVIRONMENT_ID.to_string(), cwd: cwd_uri.clone(), workspace_roots: Vec::new(), + sandbox: None, }], ) .await; diff --git a/codex-rs/core/src/guardian/prompt.rs b/codex-rs/core/src/guardian/prompt.rs index d32be1aab3..c7ff1c5e57 100644 --- a/codex-rs/core/src/guardian/prompt.rs +++ b/codex-rs/core/src/guardian/prompt.rs @@ -244,7 +244,7 @@ pub(crate) async fn build_guardian_prompt_items_with_parent_turn( fn parent_turn_denied_reads_context(turn: &TurnContext) -> Option { #[allow(deprecated)] let cwd = &turn.cwd; - let file_system_policy = turn.permission_profile.file_system_sandbox_policy(); + let file_system_policy = turn.permission_profile().file_system_sandbox_policy(); let mut entries = file_system_policy .get_unreadable_roots_with_cwd(cwd) .into_iter() diff --git a/codex-rs/core/src/guardian/tests.rs b/codex-rs/core/src/guardian/tests.rs index bc8eaf8b69..2c741df480 100644 --- a/codex-rs/core/src/guardian/tests.rs +++ b/codex-rs/core/src/guardian/tests.rs @@ -465,7 +465,7 @@ async fn build_guardian_prompt_includes_parent_turn_denied_reads() -> anyhow::Re session.thread_id = fixed_guardian_parent_session_id(); let denied_root = test_path_buf("/repo/private").abs(); let denied_glob = test_path_buf("/repo/private/**").display().to_string(); - turn.permission_profile = PermissionProfile::from_runtime_permissions( + turn.set_permission_profile_for_tests(PermissionProfile::from_runtime_permissions( &FileSystemSandboxPolicy::restricted(vec![ FileSystemSandboxEntry { path: FileSystemPath::Special { @@ -487,7 +487,7 @@ async fn build_guardian_prompt_includes_parent_turn_denied_reads() -> anyhow::Re }, ]), NetworkSandboxPolicy::Restricted, - ); + )); let session = Arc::new(session); let turn = Arc::new(turn); seed_guardian_parent_history(&session, &turn).await; diff --git a/codex-rs/core/src/mcp_openai_file.rs b/codex-rs/core/src/mcp_openai_file.rs index 59ea2c751d..389fbadb26 100644 --- a/codex-rs/core/src/mcp_openai_file.rs +++ b/codex-rs/core/src/mcp_openai_file.rs @@ -220,7 +220,8 @@ mod tests { fn set_primary_environment_cwd(turn_context: &mut TurnContext, cwd: &Path) { let cwd = AbsolutePathBuf::try_from(cwd).expect("absolute path"); - turn_context.permission_profile = codex_protocol::models::PermissionProfile::Disabled; + turn_context + .set_permission_profile_for_tests(codex_protocol::models::PermissionProfile::Disabled); let TurnEnvironmentState::Ready(primary) = &mut turn_context.environments.environments[0] else { panic!("expected ready primary environment"); diff --git a/codex-rs/core/src/mcp_tool_call_tests.rs b/codex-rs/core/src/mcp_tool_call_tests.rs index c27d51de0b..914629f515 100644 --- a/codex-rs/core/src/mcp_tool_call_tests.rs +++ b/codex-rs/core/src/mcp_tool_call_tests.rs @@ -2996,7 +2996,7 @@ async fn full_access_mode_skips_mcp_tool_approval_for_all_approval_modes() { .approval_policy .set(AskForApproval::Never) .expect("test setup should allow updating approval policy"); - turn_context.permission_profile = PermissionProfile::Disabled; + turn_context.set_permission_profile_for_tests(PermissionProfile::Disabled); let session = Arc::new(session); let turn_context = Arc::new(turn_context); diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index a3c714207a..543d29f5c8 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -243,6 +243,7 @@ use self::turn::agent_message_text; use self::turn::collect_explicit_app_ids_from_skill_items; use self::turn::realtime_text_for_event; use self::turn_context::TurnContext; +use self::turn_context::TurnEnvironmentRuntimeDefaults; use self::turn_context::TurnSkillsContext; #[cfg(test)] mod rollout_reconstruction_tests; @@ -667,6 +668,12 @@ impl Session { approvals_reviewer: config.approvals_reviewer, permission_profile_state: session_permission_profile_state_from_config(&config)?, windows_sandbox_level: WindowsSandboxLevel::from_config(&config), + environment_runtime_defaults: TurnEnvironmentRuntimeDefaults { + windows_sandbox_private_desktop: config.permissions.windows_sandbox_private_desktop, + use_legacy_landlock: config.features.use_legacy_landlock(), + allow_login_shell: config.permissions.allow_login_shell, + shell_environment_policy: config.permissions.shell_environment_policy.clone(), + }, environments: TurnEnvironmentSelections::new( config.cwd.clone(), environment_selections, @@ -950,12 +957,6 @@ impl Session { } } - fn managed_network_proxy_active_for_permission_profile( - permission_profile: &PermissionProfile, - ) -> bool { - !matches!(permission_profile, PermissionProfile::Disabled) - } - /// Builds the `x-codex-beta-features` header value for this session. /// /// `ModelClient` is session-scoped and intentionally does not depend on the full `Config`, so @@ -1479,10 +1480,16 @@ impl Session { let updated_permission_profile = updated.permission_profile(); let permission_profile_changed = previous_permission_profile != updated_permission_profile; - if updates.environments.is_some() { + let environment_settings = updated.environment_settings(); + if updates.environments.is_some() + || state.session_configuration.environment_settings() != environment_settings + { self.services .turn_environments - .update_selections(updated.environment_selections()); + .update_selections_with_settings( + updated.environment_selections(), + &environment_settings, + ); } state.session_configuration = updated; (previous_config, new_config, permission_profile_changed) diff --git a/codex-rs/core/src/session/review.rs b/codex-rs/core/src/session/review.rs index 9a89c1beeb..157d21e867 100644 --- a/codex-rs/core/src/session/review.rs +++ b/codex-rs/core/src/session/review.rs @@ -49,8 +49,7 @@ pub(super) async fn spawn_review_thread( per_turn_config.model = Some(model.clone()); per_turn_config.features = review_features.clone(); per_turn_config.permissions.shell_environment_policy = parent_turn_context - .config - .permissions + .primary_environment_settings() .shell_environment_policy .clone(); per_turn_config.codex_linux_sandbox_exe = @@ -98,8 +97,8 @@ pub(super) async fn spawn_review_thread( review_turn_id.clone(), #[allow(deprecated)] parent_turn_context.cwd.clone(), - &parent_turn_context.permission_profile, - parent_turn_context.windows_sandbox_level, + &parent_turn_context.permission_profile(), + parent_turn_context.windows_sandbox_level(), parent_turn_context.network.is_some(), )); @@ -137,9 +136,8 @@ pub(super) async fn spawn_review_thread( multi_agent_version: MultiAgentVersion::Disabled, personality: parent_turn_context.personality, approval_policy: parent_turn_context.approval_policy.clone(), - permission_profile: parent_turn_context.permission_profile(), + default_environment_settings: parent_turn_context.default_environment_settings.clone(), network: parent_turn_context.network.clone(), - windows_sandbox_level: parent_turn_context.windows_sandbox_level, #[allow(deprecated)] cwd: parent_turn_context.cwd.clone(), final_output_json_schema: None, diff --git a/codex-rs/core/src/session/rollout_reconstruction_tests.rs b/codex-rs/core/src/session/rollout_reconstruction_tests.rs index f5bf358d5a..e797b3a8fe 100644 --- a/codex-rs/core/src/session/rollout_reconstruction_tests.rs +++ b/codex-rs/core/src/session/rollout_reconstruction_tests.rs @@ -191,6 +191,7 @@ async fn record_initial_history_resumed_bare_turn_context_does_not_hydrate_previ permission_profile: None, network: None, file_system_sandbox_policy: None, + environment_sandboxes: None, model: previous_model.to_string(), comp_hash: None, personality: turn_context.personality, @@ -238,6 +239,7 @@ async fn record_initial_history_resumed_hydrates_previous_turn_settings_from_lif permission_profile: None, network: None, file_system_sandbox_policy: None, + environment_sandboxes: None, model: previous_model.to_string(), comp_hash: Some("comp-hash-a".to_string()), personality: turn_context.personality, @@ -1301,6 +1303,7 @@ async fn record_initial_history_resumed_turn_context_after_compaction_reestablis permission_profile: None, network: None, file_system_sandbox_policy: None, + environment_sandboxes: None, model: previous_model.to_string(), comp_hash: None, personality: turn_context.personality, @@ -1390,6 +1393,7 @@ async fn record_initial_history_resumed_turn_context_after_compaction_reestablis permission_profile: None, network: None, file_system_sandbox_policy: None, + environment_sandboxes: None, model: previous_model.to_string(), comp_hash: None, personality: turn_context.personality, @@ -1422,6 +1426,7 @@ async fn record_initial_history_resumed_aborted_turn_without_id_clears_active_tu permission_profile: None, network: None, file_system_sandbox_policy: None, + environment_sandboxes: None, model: previous_model.to_string(), comp_hash: None, personality: turn_context.personality, @@ -1552,6 +1557,7 @@ async fn record_initial_history_resumed_unmatched_abort_preserves_active_turn_fo permission_profile: None, network: None, file_system_sandbox_policy: None, + environment_sandboxes: None, model: current_model.to_string(), comp_hash: None, personality: turn_context.personality, @@ -1679,6 +1685,7 @@ async fn record_initial_history_resumed_trailing_incomplete_turn_compaction_clea permission_profile: None, network: None, file_system_sandbox_policy: None, + environment_sandboxes: None, model: previous_model.to_string(), comp_hash: None, personality: turn_context.personality, @@ -1849,6 +1856,7 @@ async fn record_initial_history_resumed_replaced_incomplete_compacted_turn_clear permission_profile: None, network: None, file_system_sandbox_policy: None, + environment_sandboxes: None, model: previous_model.to_string(), comp_hash: None, personality: turn_context.personality, diff --git a/codex-rs/core/src/session/session.rs b/codex-rs/core/src/session/session.rs index 04aaba64b6..1a404f37cd 100644 --- a/codex-rs/core/src/session/session.rs +++ b/codex-rs/core/src/session/session.rs @@ -4,6 +4,8 @@ use crate::agents_md_manager::AgentsMdManager; use crate::config::ConstraintError; use crate::environment_selection::ThreadEnvironments; use crate::environment_selection::TurnEnvironmentSnapshot; +use crate::session::turn_context::TurnEnvironmentRuntimeDefaults; +use crate::session::turn_context::TurnEnvironmentSettings; use crate::shell_snapshot::ShellSnapshot; use crate::skills::SkillError; use crate::state::ActiveTurn; @@ -18,7 +20,9 @@ use codex_protocol::permissions::FileSystemSpecialPath; use codex_protocol::protocol::MultiAgentVersion; use codex_protocol::protocol::ThreadHistoryMode; use codex_protocol::protocol::ThreadSource; +use codex_protocol::protocol::TurnEnvironmentSandbox; use codex_protocol::protocol::TurnEnvironmentSelections; +use std::collections::BTreeMap; use std::sync::OnceLock; use tokio::sync::Semaphore; @@ -76,6 +80,7 @@ pub(crate) struct SessionConfiguration { /// the methods below instead of mutating the fields independently. pub(super) permission_profile_state: PermissionProfileState, pub(super) windows_sandbox_level: WindowsSandboxLevel, + pub(super) environment_runtime_defaults: TurnEnvironmentRuntimeDefaults, /// Sticky thread-level environment selections plus the legacy cwd used /// when a turn does not select an environment. @@ -116,6 +121,41 @@ impl SessionConfiguration { &self.environments.environments } + pub(super) fn environment_settings(&self) -> BTreeMap { + let default_sandbox = TurnEnvironmentSandbox { + permission_profile: self.permission_profile(), + active_permission_profile: self.active_permission_profile(), + windows_sandbox_level: self.windows_sandbox_level, + windows_sandbox_private_desktop: self + .environment_runtime_defaults + .windows_sandbox_private_desktop, + use_legacy_landlock: self.environment_runtime_defaults.use_legacy_landlock, + }; + let mut settings = BTreeMap::new(); + for environment in self.environment_selections() { + settings + .entry(environment.environment_id.clone()) + .or_insert_with(|| { + let sandbox = environment + .sandbox + .as_ref() + .cloned() + .unwrap_or_else(|| default_sandbox.clone()); + self.environment_runtime_defaults.settings(sandbox) + }); + } + settings + } + + pub(super) fn uses_managed_network_proxy(&self) -> bool { + !matches!(self.permission_profile(), PermissionProfile::Disabled) + || self.environment_selections().iter().any(|environment| { + environment.sandbox.as_ref().is_some_and(|sandbox| { + !matches!(sandbox.permission_profile, PermissionProfile::Disabled) + }) + }) + } + pub(super) fn primary_workspace_roots(&self) -> Vec { self.environments .environments @@ -134,10 +174,6 @@ impl SessionConfiguration { &self.codex_home } - pub(super) fn permission_profile_state(&self) -> &PermissionProfileState { - &self.permission_profile_state - } - pub(super) fn permission_profile(&self) -> PermissionProfile { self.permission_profile_state.permission_profile().clone() } @@ -917,7 +953,10 @@ impl Session { inherited_environments.unwrap_or_default(), config.features.enabled(Feature::DeferredExecutor), )); - turn_environments.update_selections(session_configuration.environment_selections()); + turn_environments.update_selections_with_settings( + session_configuration.environment_selections(), + &session_configuration.environment_settings(), + ); let resolved_environments = turn_environments.snapshot().await; let agents_md_manager = Arc::new(AgentsMdManager::new(user_instructions)); let plugin_skill_warmup = warm_plugins_and_skills_for_session_init( @@ -1187,13 +1226,8 @@ impl Session { cwd: session_configuration.cwd().clone(), reasoning_effort: session_configuration.collaboration_mode.reasoning_effort(), initial_messages, - network_proxy: session_network_proxy.filter(|_| { - Self::managed_network_proxy_active_for_permission_profile( - session_configuration - .permission_profile_state() - .permission_profile(), - ) - }), + network_proxy: session_network_proxy + .filter(|_| session_configuration.uses_managed_network_proxy()), rollout_path, }), }) diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index f80fd944d4..986911fe10 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -1036,8 +1036,8 @@ async fn danger_full_access_turns_do_not_expose_managed_network_proxy() -> anyho #[tokio::test] async fn danger_full_access_tool_attempts_do_not_enforce_managed_network() -> anyhow::Result<()> { - #[derive(Default)] struct ProbeToolRuntime { + turn_environment: TurnEnvironment, enforce_managed_network: Vec, } @@ -1081,8 +1081,8 @@ async fn danger_full_access_tool_attempts_do_not_enforce_managed_network() -> an } impl crate::tools::sandboxing::ToolRuntime<(), ()> for ProbeToolRuntime { - fn workspace_roots<'a>(&self, _req: &'a ()) -> &'a [PathUri] { - &[] + fn turn_environment<'a>(&'a self, _req: &'a ()) -> &'a TurnEnvironment { + &self.turn_environment } async fn run( @@ -1144,7 +1144,14 @@ async fn danger_full_access_tool_attempts_do_not_enforce_managed_network() -> an assert!(turn.network.is_none()); let mut orchestrator = crate::tools::orchestrator::ToolOrchestrator::new(); - let mut tool = ProbeToolRuntime::default(); + let mut tool = ProbeToolRuntime { + turn_environment: turn + .environments + .primary() + .expect("primary environment") + .clone(), + enforce_managed_network: Vec::new(), + }; let tool_ctx = crate::tools::sandboxing::ToolCtx { session: Arc::clone(&session), turn: Arc::clone(&turn), @@ -3071,6 +3078,7 @@ async fn record_initial_history_forked_hydrates_previous_turn_settings() { permission_profile: None, network: None, file_system_sandbox_policy: None, + environment_sandboxes: None, model: previous_model.to_string(), comp_hash: None, personality: turn_context.personality, @@ -3740,6 +3748,7 @@ async fn set_rate_limits_retains_previous_credits() { approvals_reviewer: config.approvals_reviewer, permission_profile_state: config.permissions.permission_profile_state().clone(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), + environment_runtime_defaults: Default::default(), environments: TurnEnvironmentSelections::new(config.cwd.clone(), Vec::new()), codex_home: config.codex_home.clone(), thread_name: None, @@ -3849,6 +3858,7 @@ async fn set_rate_limits_updates_plan_type_when_present() { approvals_reviewer: config.approvals_reviewer, permission_profile_state: config.permissions.permission_profile_state().clone(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), + environment_runtime_defaults: Default::default(), environments: TurnEnvironmentSelections::new(config.cwd.clone(), Vec::new()), codex_home: config.codex_home.clone(), thread_name: None, @@ -4389,6 +4399,7 @@ pub(crate) async fn make_session_configuration_for_tests() -> SessionConfigurati approvals_reviewer: config.approvals_reviewer, permission_profile_state: config.permissions.permission_profile_state().clone(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), + environment_runtime_defaults: Default::default(), environments: TurnEnvironmentSelections::new(config.cwd.clone(), Vec::new()), codex_home: config.codex_home.clone(), thread_name: None, @@ -5121,6 +5132,7 @@ async fn session_new_fails_when_zsh_fork_enabled_without_packaged_zsh() { approvals_reviewer: config.approvals_reviewer, permission_profile_state: config.permissions.permission_profile_state().clone(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), + environment_runtime_defaults: Default::default(), environments: TurnEnvironmentSelections::new(config.cwd.clone(), Vec::new()), codex_home: config.codex_home.clone(), thread_name: None, @@ -5252,6 +5264,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { approvals_reviewer: config.approvals_reviewer, permission_profile_state: config.permissions.permission_profile_state().clone(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), + environment_runtime_defaults: Default::default(), environments: TurnEnvironmentSelections::new(config.cwd.clone(), default_environments), codex_home: config.codex_home.clone(), thread_name: None, @@ -5508,6 +5521,7 @@ async fn make_session_with_config_and_rx( approvals_reviewer: config.approvals_reviewer, permission_profile_state: config.permissions.permission_profile_state().clone(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), + environment_runtime_defaults: Default::default(), environments: TurnEnvironmentSelections::new(config.cwd.clone(), default_environments), codex_home: config.codex_home.clone(), thread_name: None, @@ -5615,6 +5629,7 @@ async fn make_session_with_history_source_and_agent_control_and_rx( approvals_reviewer: config.approvals_reviewer, permission_profile_state: config.permissions.permission_profile_state().clone(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), + environment_runtime_defaults: Default::default(), environments: TurnEnvironmentSelections::new(config.cwd.clone(), default_environments), codex_home: config.codex_home.clone(), thread_name: None, @@ -7411,6 +7426,7 @@ where approvals_reviewer: config.approvals_reviewer, permission_profile_state: config.permissions.permission_profile_state().clone(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), + environment_runtime_defaults: Default::default(), environments: TurnEnvironmentSelections::new(config.cwd.clone(), default_environments), codex_home: config.codex_home.clone(), thread_name: None, @@ -8824,10 +8840,12 @@ async fn turn_context_item_omits_legacy_equivalent_file_system_sandbox_policy() async fn turn_context_item_stores_split_file_system_sandbox_policy_when_different() { let (_session, mut turn_context) = make_session_and_context().await; let file_system_sandbox_policy = file_system_policy_with_unreadable_glob(&turn_context); - turn_context.permission_profile = PermissionProfile::from_runtime_permissions_with_enforcement( - turn_context.permission_profile.enforcement(), - &file_system_sandbox_policy, - turn_context.network_sandbox_policy(), + turn_context.set_permission_profile_for_tests( + PermissionProfile::from_runtime_permissions_with_enforcement( + turn_context.permission_profile().enforcement(), + &file_system_sandbox_policy, + turn_context.network_sandbox_policy(), + ), ); let item = turn_context.to_turn_context_item(); @@ -8982,10 +9000,12 @@ async fn record_context_updates_and_set_reference_context_item_persists_split_fi { let (mut session, mut turn_context) = make_session_and_context().await; let file_system_sandbox_policy = file_system_policy_with_unreadable_glob(&turn_context); - turn_context.permission_profile = PermissionProfile::from_runtime_permissions_with_enforcement( - turn_context.permission_profile.enforcement(), - &file_system_sandbox_policy, - turn_context.network_sandbox_policy(), + turn_context.set_permission_profile_for_tests( + PermissionProfile::from_runtime_permissions_with_enforcement( + turn_context.permission_profile().enforcement(), + &file_system_sandbox_policy, + turn_context.network_sandbox_policy(), + ), ); let rollout_path = attach_thread_persistence(&mut session).await; @@ -10746,7 +10766,7 @@ async fn rejects_escalated_permissions_when_policy_not_on_request() { // command. Force DangerFullAccess so this check stays focused on approval // policy rather than platform-specific sandbox behavior. let turn_context_mut = Arc::get_mut(&mut turn_context).expect("unique thread settings Arc"); - turn_context_mut.permission_profile = PermissionProfile::Disabled; + turn_context_mut.set_permission_profile_for_tests(PermissionProfile::Disabled); let command = session.user_shell().derive_exec_args( command_script, @@ -10759,7 +10779,7 @@ async fn rejects_escalated_permissions_when_policy_not_on_request() { command: &command, approval_policy: turn_context.approval_policy.value(), permission_profile: turn_context.permission_profile(), - windows_sandbox_level: turn_context.windows_sandbox_level, + windows_sandbox_level: turn_context.windows_sandbox_level(), sandbox_permissions: SandboxPermissions::UseDefault, prefix_rule: None, }) diff --git a/codex-rs/core/src/session/tests/guardian_tests.rs b/codex-rs/core/src/session/tests/guardian_tests.rs index d2cee609f1..60f69f1b1f 100644 --- a/codex-rs/core/src/session/tests/guardian_tests.rs +++ b/codex-rs/core/src/session/tests/guardian_tests.rs @@ -301,7 +301,8 @@ async fn guardian_allows_shell_command_additional_permissions_requests_past_poli .features .enable(Feature::ExecPermissionApprovals) .expect("test setup should allow enabling request permissions"); - turn_context_raw.permission_profile = codex_protocol::models::PermissionProfile::Disabled; + turn_context_raw + .set_permission_profile_for_tests(codex_protocol::models::PermissionProfile::Disabled); let mut config = (*turn_context_raw.config).clone(); config .permissions @@ -416,7 +417,8 @@ async fn strict_auto_review_turn_grant_forces_guardian_for_shell_command_policy_ .approval_policy .set(AskForApproval::Never) .expect("test setup should allow updating approval policy"); - turn_context_raw.permission_profile = codex_protocol::models::PermissionProfile::Disabled; + turn_context_raw + .set_permission_profile_for_tests(codex_protocol::models::PermissionProfile::Disabled); let mut config = (*turn_context_raw.config).clone(); config .permissions diff --git a/codex-rs/core/src/session/turn_context.rs b/codex-rs/core/src/session/turn_context.rs index 07a6fdb005..6537efd539 100644 --- a/codex-rs/core/src/session/turn_context.rs +++ b/codex-rs/core/src/session/turn_context.rs @@ -7,11 +7,13 @@ use codex_model_provider::SharedModelProvider; use codex_model_provider::create_model_provider; use codex_protocol::SessionId; use codex_protocol::ThreadId; +use codex_protocol::config_types::ShellEnvironmentPolicy; use codex_protocol::models::AdditionalPermissionProfile; use codex_protocol::openai_models::ModelInfo; use codex_protocol::protocol::ErrorEvent; use codex_protocol::protocol::MultiAgentVersion; use codex_protocol::protocol::ThreadHistoryMode; +use codex_protocol::protocol::TurnEnvironmentSandbox; use codex_protocol::protocol::TurnEnvironmentSelection; use codex_sandboxing::compatibility_sandbox_policy_for_permission_profile; use codex_sandboxing::policy_transforms::effective_file_system_sandbox_policy; @@ -41,29 +43,100 @@ impl TurnSkillsContext { pub(crate) type ShellSnapshotTask = Shared>>>; +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct TurnEnvironmentSettings { + pub(crate) sandbox: TurnEnvironmentSandbox, + pub(crate) allow_login_shell: bool, + pub(crate) shell_environment_policy: ShellEnvironmentPolicy, +} + +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct TurnEnvironmentRuntimeDefaults { + pub(crate) windows_sandbox_private_desktop: bool, + pub(crate) use_legacy_landlock: bool, + pub(crate) allow_login_shell: bool, + pub(crate) shell_environment_policy: ShellEnvironmentPolicy, +} + +impl Default for TurnEnvironmentRuntimeDefaults { + fn default() -> Self { + Self { + windows_sandbox_private_desktop: false, + use_legacy_landlock: false, + allow_login_shell: true, + shell_environment_policy: ShellEnvironmentPolicy::default(), + } + } +} + +impl TurnEnvironmentRuntimeDefaults { + pub(crate) fn settings(&self, sandbox: TurnEnvironmentSandbox) -> TurnEnvironmentSettings { + TurnEnvironmentSettings { + sandbox, + allow_login_shell: self.allow_login_shell, + shell_environment_policy: self.shell_environment_policy.clone(), + } + } +} + +impl Default for TurnEnvironmentSettings { + fn default() -> Self { + Self { + sandbox: TurnEnvironmentSandbox::default(), + allow_login_shell: true, + shell_environment_policy: ShellEnvironmentPolicy::default(), + } + } +} + #[derive(Clone)] pub(crate) struct TurnEnvironment { pub(crate) environment_id: String, pub(crate) environment: Arc, cwd: PathUri, workspace_roots: Vec, + sandbox_override: Option, + pub(crate) settings: TurnEnvironmentSettings, pub(crate) shell: Option, pub(crate) shell_snapshot: ShellSnapshotTask, } impl TurnEnvironment { + #[cfg(test)] pub(crate) fn new( environment_id: String, environment: Arc, cwd: PathUri, workspace_roots: Vec, shell: Option, + ) -> Self { + Self::new_with_settings( + environment_id, + environment, + cwd, + workspace_roots, + /*sandbox_override*/ None, + TurnEnvironmentSettings::default(), + shell, + ) + } + + pub(crate) fn new_with_settings( + environment_id: String, + environment: Arc, + cwd: PathUri, + workspace_roots: Vec, + sandbox_override: Option, + settings: TurnEnvironmentSettings, + shell: Option, ) -> Self { Self { environment_id, environment, cwd, workspace_roots, + sandbox_override, + settings, shell, shell_snapshot: futures::future::ready(None).boxed().shared(), } @@ -87,11 +160,62 @@ impl TurnEnvironment { &self.workspace_roots } + pub(crate) fn permission_profile(&self) -> &PermissionProfile { + &self.settings.sandbox.permission_profile + } + + pub(crate) fn active_permission_profile(&self) -> Option { + self.settings.sandbox.active_permission_profile.clone() + } + + pub(crate) fn file_system_sandbox_policy(&self) -> FileSystemSandboxPolicy { + self.permission_profile().file_system_sandbox_policy() + } + + pub(crate) fn network_sandbox_policy(&self) -> NetworkSandboxPolicy { + self.permission_profile().network_sandbox_policy() + } + + pub(crate) fn uses_managed_network_proxy(&self) -> bool { + !matches!(self.permission_profile(), PermissionProfile::Disabled) + } + + pub(crate) fn file_system_sandbox_context( + &self, + additional_permissions: Option, + ) -> FileSystemSandboxContext { + let permission_profile = self.permission_profile(); + let (base_file_system_sandbox_policy, base_network_sandbox_policy) = + permission_profile.to_runtime_permissions(); + let file_system_sandbox_policy = effective_file_system_sandbox_policy( + &base_file_system_sandbox_policy, + additional_permissions.as_ref(), + ); + let network_sandbox_policy = effective_network_sandbox_policy( + base_network_sandbox_policy, + additional_permissions.as_ref(), + ); + let permissions = PermissionProfile::from_runtime_permissions_with_enforcement( + permission_profile.enforcement(), + &file_system_sandbox_policy, + network_sandbox_policy, + ); + FileSystemSandboxContext { + permissions: permissions.into(), + cwd: Some(self.cwd().clone()), + workspace_roots: self.workspace_roots().to_vec(), + windows_sandbox_level: self.settings.sandbox.windows_sandbox_level, + windows_sandbox_private_desktop: self.settings.sandbox.windows_sandbox_private_desktop, + use_legacy_landlock: self.settings.sandbox.use_legacy_landlock, + } + } + pub(crate) fn selection(&self) -> TurnEnvironmentSelection { TurnEnvironmentSelection { environment_id: self.environment_id.clone(), cwd: self.cwd.clone(), workspace_roots: self.workspace_roots.clone(), + sandbox: self.sandbox_override.clone(), } } } @@ -103,6 +227,8 @@ impl std::fmt::Debug for TurnEnvironment { .field("environment", &self.environment) .field("cwd", &self.cwd) .field("workspace_roots", &self.workspace_roots) + .field("sandbox_override", &self.sandbox_override) + .field("settings", &self.settings) .field("shell", &self.shell) .finish_non_exhaustive() } @@ -140,9 +266,8 @@ pub struct TurnContext { pub(crate) multi_agent_version: MultiAgentVersion, pub(crate) personality: Option, pub(crate) approval_policy: Constrained, - pub(crate) permission_profile: PermissionProfile, + pub(crate) default_environment_settings: TurnEnvironmentSettings, pub(crate) network: Option, - pub(crate) windows_sandbox_level: WindowsSandboxLevel, pub(crate) available_models: Vec, pub(crate) unified_exec_shell_mode: UnifiedExecShellMode, pub(crate) final_output_json_schema: Option, @@ -178,21 +303,55 @@ impl TurnContext { } } + pub(crate) fn primary_environment_settings(&self) -> &TurnEnvironmentSettings { + self.environments + .primary() + .map(|environment| &environment.settings) + .unwrap_or(&self.default_environment_settings) + } + pub(crate) fn permission_profile(&self) -> PermissionProfile { - self.permission_profile.clone() + self.primary_environment_settings() + .sandbox + .permission_profile + .clone() + } + + #[cfg(test)] + pub(crate) fn set_permission_profile_for_tests( + &mut self, + permission_profile: PermissionProfile, + ) { + self.default_environment_settings.sandbox.permission_profile = permission_profile.clone(); + for environment in &mut self.environments.environments { + match environment { + crate::environment_selection::TurnEnvironmentState::Ready(environment) => { + environment.settings.sandbox.permission_profile = permission_profile.clone(); + } + crate::environment_selection::TurnEnvironmentState::Starting(environment) => { + environment.settings.sandbox.permission_profile = permission_profile.clone(); + } + } + } + } + + pub(crate) fn windows_sandbox_level(&self) -> WindowsSandboxLevel { + self.primary_environment_settings() + .sandbox + .windows_sandbox_level } pub(crate) fn file_system_sandbox_policy(&self) -> FileSystemSandboxPolicy { - self.permission_profile.file_system_sandbox_policy() + self.permission_profile().file_system_sandbox_policy() } pub(crate) fn network_sandbox_policy(&self) -> NetworkSandboxPolicy { - self.permission_profile.network_sandbox_policy() + self.permission_profile().network_sandbox_policy() } pub(crate) fn sandbox_policy(&self) -> SandboxPolicy { compatibility_sandbox_policy_for_permission_profile( - &self.permission_profile, + &self.permission_profile(), #[allow(deprecated)] &self.cwd, ) @@ -302,9 +461,8 @@ impl TurnContext { multi_agent_version: self.multi_agent_version, personality: self.personality, approval_policy: self.approval_policy.clone(), - permission_profile: self.permission_profile.clone(), + default_environment_settings: self.default_environment_settings.clone(), network: self.network.clone(), - windows_sandbox_level: self.windows_sandbox_level, available_models, unified_exec_shell_mode: self.unified_exec_shell_mode.clone(), final_output_json_schema: self.final_output_json_schema.clone(), @@ -323,40 +481,6 @@ impl TurnContext { } } - pub(crate) fn file_system_sandbox_context( - &self, - additional_permissions: Option, - environment: &TurnEnvironment, - ) -> FileSystemSandboxContext { - let permission_profile = self.config.permissions.permission_profile(); - let (base_file_system_sandbox_policy, base_network_sandbox_policy) = - permission_profile.to_runtime_permissions(); - let file_system_sandbox_policy = effective_file_system_sandbox_policy( - &base_file_system_sandbox_policy, - additional_permissions.as_ref(), - ); - let network_sandbox_policy = effective_network_sandbox_policy( - base_network_sandbox_policy, - additional_permissions.as_ref(), - ); - let permissions = PermissionProfile::from_runtime_permissions_with_enforcement( - permission_profile.enforcement(), - &file_system_sandbox_policy, - network_sandbox_policy, - ); - FileSystemSandboxContext { - permissions: permissions.into(), - cwd: Some(environment.cwd().clone()), - workspace_roots: environment.workspace_roots().to_vec(), - windows_sandbox_level: self.windows_sandbox_level, - windows_sandbox_private_desktop: self - .config - .permissions - .windows_sandbox_private_desktop, - use_legacy_landlock: self.config.features.use_legacy_landlock(), - } - } - fn non_legacy_file_system_sandbox_policy(&self) -> Option { // Omit the derived split filesystem policy when it is equivalent to // the legacy sandbox policy. This keeps turn-context payloads stable @@ -375,6 +499,7 @@ impl TurnContext { pub(crate) fn to_turn_context_item(&self) -> TurnContextItem { let workspace_roots = self.config.effective_workspace_roots(); + let environment_sandboxes = self.environments.environment_sandboxes(); #[allow(deprecated)] let cwd = self.cwd.clone(); TurnContextItem { @@ -389,6 +514,8 @@ impl TurnContext { permission_profile: Some(self.permission_profile()), network: self.turn_context_network_item(), file_system_sandbox_policy: self.non_legacy_file_system_sandbox_policy(), + environment_sandboxes: (!environment_sandboxes.is_empty()) + .then_some(environment_sandboxes), model: self.model_info.slug.clone(), comp_hash: self.model_info.comp_hash.clone(), personality: self.personality, @@ -533,7 +660,28 @@ impl Session { per_turn_config.features.enabled(Feature::FastMode), &model_info, ); - let permission_profile = per_turn_config.permissions.effective_permission_profile(); + let default_environment_settings = session_configuration + .environment_runtime_defaults + .settings(TurnEnvironmentSandbox { + permission_profile: session_configuration.permission_profile(), + active_permission_profile: session_configuration.active_permission_profile(), + windows_sandbox_level: session_configuration.windows_sandbox_level, + windows_sandbox_private_desktop: session_configuration + .environment_runtime_defaults + .windows_sandbox_private_desktop, + use_legacy_landlock: session_configuration + .environment_runtime_defaults + .use_legacy_landlock, + }); + let primary_environment_settings = environments + .primary() + .map(|environment| &environment.settings) + .unwrap_or(&default_environment_settings); + let permission_profile = primary_environment_settings + .sandbox + .permission_profile + .clone(); + let windows_sandbox_level = primary_environment_settings.sandbox.windows_sandbox_level; let per_turn_config = Arc::new(per_turn_config); let turn_metadata_state = Arc::new(TurnMetadataState::new( session_id.to_string(), @@ -545,7 +693,7 @@ impl Session { sub_id.clone(), cwd.clone(), &permission_profile, - session_configuration.windows_sandbox_level, + windows_sandbox_level, network.is_some(), )); let (current_date, timezone) = local_time_context(); @@ -581,9 +729,8 @@ impl Session { multi_agent_version, personality: session_configuration.personality, approval_policy: session_configuration.approval_policy.clone(), - permission_profile, + default_environment_settings, network, - windows_sandbox_level: session_configuration.windows_sandbox_level, available_models, unified_exec_shell_mode, final_output_json_schema: None, @@ -618,10 +765,17 @@ impl Session { }); let new_config = notify_config_contributors .then(|| Self::build_effective_session_config(&next)); - if updates.environments.is_some() { + let environment_settings = next.environment_settings(); + if updates.environments.is_some() + || state.session_configuration.environment_settings() + != environment_settings + { self.services .turn_environments - .update_selections(next.environment_selections()); + .update_selections_with_settings( + next.environment_selections(), + &environment_settings, + ); } state.session_configuration = next.clone(); Ok(( @@ -780,12 +934,7 @@ impl Session { .network_proxy .load_full() .as_ref() - .and_then(|started_proxy| { - Self::managed_network_proxy_active_for_permission_profile( - &session_configuration.permission_profile(), - ) - .then(|| started_proxy.proxy()) - }), + .map(|started_proxy| started_proxy.proxy()), turn_environments, cwd, sub_id, diff --git a/codex-rs/core/src/tasks/user_shell.rs b/codex-rs/core/src/tasks/user_shell.rs index 99f32580e1..9417f21336 100644 --- a/codex-rs/core/src/tasks/user_shell.rs +++ b/codex-rs/core/src/tasks/user_shell.rs @@ -157,7 +157,7 @@ pub(crate) async fn execute_user_shell_command( }; let shell_snapshot_location = turn_environment.shell_snapshot(&cwd); let mut exec_env_map = create_env( - &turn_context.config.permissions.shell_environment_policy, + &turn_environment.settings.shell_environment_policy, Some(session.thread_id), ); if exec_env_map.contains_key(PROXY_ACTIVE_ENV_KEY) { @@ -167,11 +167,7 @@ pub(crate) async fn execute_user_shell_command( &display_command, environment_shell, shell_snapshot_location.as_ref(), - &turn_context - .config - .permissions - .shell_environment_policy - .r#set, + &turn_environment.settings.shell_environment_policy.r#set, &mut exec_env_map, ); @@ -201,6 +197,11 @@ pub(crate) async fn execute_user_shell_command( ) .await; + let windows_sandbox_workspace_roots = turn_environment + .workspace_roots() + .iter() + .filter_map(|root| root.to_abs_path().ok()) + .collect(); let permission_profile = PermissionProfile::Disabled; let exec_env = ExecRequest { command: exec_command.clone(), @@ -217,11 +218,11 @@ pub(crate) async fn execute_user_shell_command( capture_policy: ExecCapturePolicy::ShellTool, sandbox: SandboxType::None, windows_sandbox_policy_cwd: cwd.clone().into(), - windows_sandbox_workspace_roots: turn_context.config.effective_workspace_roots(), - windows_sandbox_level: turn_context.windows_sandbox_level, - windows_sandbox_private_desktop: turn_context - .config - .permissions + windows_sandbox_workspace_roots, + windows_sandbox_level: turn_environment.settings.sandbox.windows_sandbox_level, + windows_sandbox_private_desktop: turn_environment + .settings + .sandbox .windows_sandbox_private_desktop, permission_profile: permission_profile.clone(), file_system_sandbox_policy: permission_profile.file_system_sandbox_policy(), diff --git a/codex-rs/core/src/thread_manager_tests.rs b/codex-rs/core/src/thread_manager_tests.rs index 2c3bfd80ea..5176af8262 100644 --- a/codex-rs/core/src/thread_manager_tests.rs +++ b/codex-rs/core/src/thread_manager_tests.rs @@ -860,6 +860,7 @@ async fn resume_and_fork_do_not_restore_thread_environments_from_rollout() { environment_id: "local".to_string(), cwd: PathUri::from_abs_path(&selected_cwd), workspace_roots: Vec::new(), + sandbox: None, }]; let default_cwd = config.cwd.clone(); let mut source_config = config.clone(); diff --git a/codex-rs/core/src/tools/handlers/apply_patch.rs b/codex-rs/core/src/tools/handlers/apply_patch.rs index 0950174ba4..ec6ea2f141 100644 --- a/codex-rs/core/src/tools/handlers/apply_patch.rs +++ b/codex-rs/core/src/tools/handlers/apply_patch.rs @@ -260,7 +260,7 @@ fn apply_patch_payload_command(payload: &ToolPayload) -> Option { async fn effective_patch_permissions( session: &Session, - turn: &TurnContext, + turn_environment: &TurnEnvironment, environment_id: &str, action: &ApplyPatchAction, cwd: &PathUri, @@ -281,7 +281,7 @@ async fn effective_patch_permissions( .await .as_ref(), ); - let base_file_system_sandbox_policy = turn.file_system_sandbox_policy(); + let base_file_system_sandbox_policy = turn_environment.file_system_sandbox_policy(); let file_system_sandbox_policy = effective_file_system_sandbox_policy( &base_file_system_sandbox_policy, granted_permissions.as_ref(), @@ -383,8 +383,8 @@ impl ApplyPatchHandler { )); }; let fs = turn_environment.environment.get_filesystem(); - let sandbox = turn - .file_system_sandbox_context(/*additional_permissions*/ None, turn_environment); + let sandbox = + turn_environment.file_system_sandbox_context(/*additional_permissions*/ None); match codex_apply_patch::verify_apply_patch_args( args, turn_environment.cwd(), @@ -397,15 +397,20 @@ impl ApplyPatchHandler { let (file_paths, effective_additional_permissions, file_system_sandbox_policy) = effective_patch_permissions( session.as_ref(), - turn.as_ref(), + turn_environment, &turn_environment.environment_id, &changes, turn_environment.cwd(), ) .await .unwrap_or_else(|_| patch_permissions_without_path_matching(&changes)); - match apply_patch::apply_patch(turn.as_ref(), &file_system_sandbox_policy, changes) - .await + match apply_patch::apply_patch( + turn.as_ref(), + turn_environment, + &file_system_sandbox_policy, + changes, + ) + .await { InternalApplyPatchInvocation::Output(item) => { let content = item?; @@ -553,7 +558,7 @@ pub(crate) async fn intercept_apply_patch( tool_name: &str, ) -> Result, FunctionCallError> { let sandbox = - turn.file_system_sandbox_context(/*additional_permissions*/ None, &turn_environment); + turn_environment.file_system_sandbox_context(/*additional_permissions*/ None); match codex_apply_patch::maybe_parse_apply_patch_verified(command, cwd, fs, Some(&sandbox)) .await { @@ -561,15 +566,20 @@ pub(crate) async fn intercept_apply_patch( let (approval_keys, effective_additional_permissions, file_system_sandbox_policy) = effective_patch_permissions( session.as_ref(), - turn.as_ref(), + &turn_environment, &turn_environment.environment_id, &changes, cwd, ) .await .unwrap_or_else(|_| patch_permissions_without_path_matching(&changes)); - match apply_patch::apply_patch(turn.as_ref(), &file_system_sandbox_policy, changes) - .await + match apply_patch::apply_patch( + turn.as_ref(), + &turn_environment, + &file_system_sandbox_policy, + changes, + ) + .await { InternalApplyPatchInvocation::Output(item) => { let content = item?; diff --git a/codex-rs/core/src/tools/handlers/extension_tools.rs b/codex-rs/core/src/tools/handlers/extension_tools.rs index 7d31f08c21..2c1503fed7 100644 --- a/codex-rs/core/src/tools/handlers/extension_tools.rs +++ b/codex-rs/core/src/tools/handlers/extension_tools.rs @@ -140,9 +140,8 @@ async fn to_extension_call(invocation: &ToolInvocation) -> ExtensionToolCall { ) .await .additional_permissions; - let file_system_sandbox_context = invocation - .turn - .file_system_sandbox_context(additional_permissions, environment); + let file_system_sandbox_context = + environment.file_system_sandbox_context(additional_permissions); environments.push(ToolEnvironment { environment_id: environment.environment_id.clone(), cwd: native_cwd, diff --git a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs index 55a24254da..458e05adae 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_tests.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_tests.rs @@ -2296,7 +2296,7 @@ async fn spawn_agent_reapplies_runtime_sandbox_after_role_config() { let mut config = (*turn.config).clone(); config.approvals_reviewer = ApprovalsReviewer::AutoReview; set_turn_config(&mut turn, config); - turn.permission_profile = expected_permission_profile.clone(); + turn.set_permission_profile_for_tests(expected_permission_profile.clone()); assert_ne!( expected_permission_profile, turn.config.permissions.effective_permission_profile(), @@ -4456,7 +4456,7 @@ async fn build_agent_spawn_config_uses_turn_context_values() { &file_system_sandbox_policy, network_sandbox_policy, ); - turn.permission_profile = permission_profile.clone(); + turn.set_permission_profile_for_tests(permission_profile.clone()); turn.approval_policy .set(AskForApproval::OnRequest) .expect("approval policy set"); diff --git a/codex-rs/core/src/tools/handlers/shell.rs b/codex-rs/core/src/tools/handlers/shell.rs index 87a9301093..0db26c970f 100644 --- a/codex-rs/core/src/tools/handlers/shell.rs +++ b/codex-rs/core/src/tools/handlers/shell.rs @@ -171,8 +171,8 @@ async fn run_exec_like(args: RunExecLikeArgs) -> Result Result { let session_shell = session.user_shell(); let shell = turn_environment .shell .as_ref() .unwrap_or(session_shell.as_ref()); - let use_login_shell = Self::resolve_use_login_shell(params.login, allow_login_shell)?; + let use_login_shell = Self::resolve_use_login_shell( + params.login, + turn_environment.settings.allow_login_shell, + )?; let command = Self::base_command(shell, ¶ms.command, use_login_shell); let mut env = create_env( - &turn_context.config.permissions.shell_environment_policy, + &turn_environment.settings.shell_environment_policy, Some(session.thread_id), ); - let active_permission_profile = turn_context.config.permissions.active_permission_profile(); + let active_permission_profile = turn_environment.active_permission_profile(); inject_permission_profile_env(&mut env, active_permission_profile.as_ref()); Ok(ExecParams { @@ -113,13 +115,16 @@ impl ShellCommandHandler { expiration: params.timeout_ms.into(), capture_policy: ExecCapturePolicy::ShellTool, env, - network: turn_context.network.clone(), + network: turn_environment + .uses_managed_network_proxy() + .then(|| turn_context.network.clone()) + .flatten(), network_environment_id: Some(turn_environment.environment_id.clone()), sandbox_permissions: params.sandbox_permissions.unwrap_or_default(), - windows_sandbox_level: turn_context.windows_sandbox_level, - windows_sandbox_private_desktop: turn_context - .config - .permissions + windows_sandbox_level: turn_environment.settings.sandbox.windows_sandbox_level, + windows_sandbox_private_desktop: turn_environment + .settings + .sandbox .windows_sandbox_private_desktop, justification: params.justification.clone(), arg0: None, @@ -209,7 +214,6 @@ impl ShellCommandHandler { turn.as_ref(), &turn_environment, cwd, - turn.config.permissions.allow_login_shell, )?; let shell_type = Some( turn_environment diff --git a/codex-rs/core/src/tools/handlers/shell_tests.rs b/codex-rs/core/src/tools/handlers/shell_tests.rs index 90fd27d878..5a94b48824 100644 --- a/codex-rs/core/src/tools/handlers/shell_tests.rs +++ b/codex-rs/core/src/tools/handlers/shell_tests.rs @@ -99,7 +99,9 @@ async fn shell_command_handler_to_exec_params_uses_selected_environment() { let expected_command = selected_shell.derive_exec_args(&command, /*use_login_shell*/ true); let selected_cwd = turn_context.config.cwd.join("selected-environment"); let expected_cwd = selected_cwd.join("subdir"); - let selected_environment = TurnEnvironment::new( + let mut selected_environment_settings = turn_context.primary_environment_settings().clone(); + selected_environment_settings.allow_login_shell = true; + let selected_environment = TurnEnvironment::new_with_settings( "selected-environment".to_string(), Arc::clone( &turn_context @@ -110,13 +112,15 @@ async fn shell_command_handler_to_exec_params_uses_selected_environment() { ), PathUri::from_abs_path(&selected_cwd), Vec::new(), + /*sandbox_override*/ None, + selected_environment_settings, Some(selected_shell), ); let mut expected_env = create_env( - &turn_context.config.permissions.shell_environment_policy, + &selected_environment.settings.shell_environment_policy, Some(session.thread_id), ); - let active_permission_profile = turn_context.config.permissions.active_permission_profile(); + let active_permission_profile = selected_environment.active_permission_profile(); inject_permission_profile_env(&mut expected_env, active_permission_profile.as_ref()); let params = ShellCommandToolCallParams { @@ -136,7 +140,6 @@ async fn shell_command_handler_to_exec_params_uses_selected_environment() { &turn_context, &selected_environment, expected_cwd.clone(), - /*allow_login_shell*/ true, ) .expect("login shells should be allowed"); @@ -217,7 +220,6 @@ async fn shell_command_handler_defaults_to_non_login_when_disallowed() { &turn_context, turn_environment, cwd, - /*allow_login_shell*/ false, ) .expect("non-login shells should still be allowed"); diff --git a/codex-rs/core/src/tools/handlers/unified_exec/exec_command.rs b/codex-rs/core/src/tools/handlers/unified_exec/exec_command.rs index fc48f1ed81..aec094c34b 100644 --- a/codex-rs/core/src/tools/handlers/unified_exec/exec_command.rs +++ b/codex-rs/core/src/tools/handlers/unified_exec/exec_command.rs @@ -155,10 +155,10 @@ impl ExecCommandHandler { // permissions config below. Consult the configured platform-sandbox requirement before // deciding whether parsing may continue without that base path. let sandbox = SandboxManager::new().select_initial( - &turn.file_system_sandbox_policy(), - turn.network_sandbox_policy(), + &turn_environment.file_system_sandbox_policy(), + turn_environment.network_sandbox_policy(), SandboxablePreference::Auto, - turn.windows_sandbox_level, + turn_environment.settings.sandbox.windows_sandbox_level, turn.network.is_some(), ); // `to_abs_path()` alone cannot identify foreign drive paths: `file:///C:/repo` is @@ -233,7 +233,7 @@ impl ExecCommandHandler { &args, shell, &shell_mode, - turn.config.permissions.allow_login_shell, + turn_environment.settings.allow_login_shell, ) .map_err(FunctionCallError::RespondToModel)?; let command = resolved_command.command; @@ -354,7 +354,10 @@ impl ExecCommandHandler { sandbox_cwd: native_environment_cwd, turn_environment: turn_environment.clone(), shell_mode, - network: context.turn.network.clone(), + network: turn_environment + .uses_managed_network_proxy() + .then(|| context.turn.network.clone()) + .flatten(), tty, sandbox_permissions: effective_additional_permissions.sandbox_permissions, additional_permissions: normalized_additional_permissions, diff --git a/codex-rs/core/src/tools/handlers/view_image.rs b/codex-rs/core/src/tools/handlers/view_image.rs index 20efe1b549..7686600170 100644 --- a/codex-rs/core/src/tools/handlers/view_image.rs +++ b/codex-rs/core/src/tools/handlers/view_image.rs @@ -147,8 +147,8 @@ impl ViewImageHandler { )) })?; let model_visible_path = path_uri.inferred_native_path_string(); - let sandbox = turn - .file_system_sandbox_context(/*additional_permissions*/ None, turn_environment); + let sandbox = + turn_environment.file_system_sandbox_context(/*additional_permissions*/ None); let fs = turn_environment.environment.get_filesystem(); let metadata = fs @@ -315,7 +315,7 @@ mod tests { replace_primary_environment_cwd(&mut turn, image_cwd.clone()); let image_path = image_cwd.join("image.png"); std::fs::write(image_path.as_path(), b"not a real image").expect("write test image"); - turn.permission_profile = PermissionProfile::read_only(); + turn.set_permission_profile_for_tests(PermissionProfile::read_only()); let turn = Arc::new(turn); let result = ViewImageHandler::default() diff --git a/codex-rs/core/src/tools/network_approval.rs b/codex-rs/core/src/tools/network_approval.rs index a6eb1d55a7..7d533920a8 100644 --- a/codex-rs/core/src/tools/network_approval.rs +++ b/codex-rs/core/src/tools/network_approval.rs @@ -571,7 +571,13 @@ impl NetworkApprovalService { } return NetworkDecision::deny(REASON_NOT_ALLOWED); }; - if !permission_profile_allows_network_approval_flow(&turn_context.permission_profile()) { + let permission_profile = turn_context + .environments + .turn_environments() + .find(|environment| environment.environment_id == environment_id) + .map(|environment| environment.permission_profile().clone()) + .unwrap_or_else(|| turn_context.permission_profile()); + if !permission_profile_allows_network_approval_flow(&permission_profile) { pending.set_decision(PendingApprovalDecision::Deny).await; self.pending_host_approvals.lock().await.remove(&key); if let Some(owner_call) = owner_call.as_ref() { diff --git a/codex-rs/core/src/tools/orchestrator.rs b/codex-rs/core/src/tools/orchestrator.rs index 810b0eb9b6..ebd81a358b 100644 --- a/codex-rs/core/src/tools/orchestrator.rs +++ b/codex-rs/core/src/tools/orchestrator.rs @@ -151,8 +151,10 @@ impl ToolOrchestrator { // 1) Approval let mut already_approved = false; - let workspace_roots = tool.workspace_roots(req); - let permission_profile = turn_ctx.config.permissions.permission_profile(); + let turn_environment = tool.turn_environment(req).clone(); + let workspace_roots = turn_environment.workspace_roots(); + let settings = &turn_environment.settings; + let permission_profile = turn_environment.permission_profile(); let materialized_workspace_roots = workspace_roots .iter() .filter_map(|workspace_root| workspace_root.to_abs_path().ok()) @@ -230,7 +232,8 @@ impl ToolOrchestrator { &requirement, &file_system_sandbox_policy, ); - let managed_network_active = turn_ctx.network.is_some(); + let managed_network_active = + turn_ctx.network.is_some() && turn_environment.uses_managed_network_proxy(); let sandbox_preference = tool.sandbox_preference(); let sandbox_requested = match sandbox_override { SandboxOverride::BypassSandboxFirstAttempt => false, @@ -246,7 +249,7 @@ impl ToolOrchestrator { &file_system_sandbox_policy, network_sandbox_policy, sandbox_preference, - turn_ctx.windows_sandbox_level, + settings.sandbox.windows_sandbox_level, managed_network_active, ) } else { @@ -254,7 +257,7 @@ impl ToolOrchestrator { }; // Platform-specific flag gating is handled by SandboxManager::select_initial. - let use_legacy_landlock = turn_ctx.config.features.use_legacy_landlock(); + let use_legacy_landlock = settings.sandbox.use_legacy_landlock; #[allow(deprecated)] let sandbox_policy_cwd = tool .sandbox_cwd(req) @@ -271,11 +274,8 @@ impl ToolOrchestrator { workspace_roots, codex_linux_sandbox_exe: turn_ctx.config.codex_linux_sandbox_exe.as_ref(), use_legacy_landlock, - windows_sandbox_level: turn_ctx.windows_sandbox_level, - windows_sandbox_private_desktop: turn_ctx - .config - .permissions - .windows_sandbox_private_desktop, + windows_sandbox_level: settings.sandbox.windows_sandbox_level, + windows_sandbox_private_desktop: settings.sandbox.windows_sandbox_private_desktop, network_denial_cancellation_token: None, network_proxy: None, }; @@ -431,7 +431,7 @@ impl ToolOrchestrator { &file_system_sandbox_policy, network_sandbox_policy, sandbox_preference, - turn_ctx.windows_sandbox_level, + settings.sandbox.windows_sandbox_level, managed_network_active, ) } else { @@ -453,10 +453,9 @@ impl ToolOrchestrator { workspace_roots, codex_linux_sandbox_exe: retry_codex_linux_sandbox_exe, use_legacy_landlock, - windows_sandbox_level: turn_ctx.windows_sandbox_level, - windows_sandbox_private_desktop: turn_ctx - .config - .permissions + windows_sandbox_level: settings.sandbox.windows_sandbox_level, + windows_sandbox_private_desktop: settings + .sandbox .windows_sandbox_private_desktop, network_denial_cancellation_token: None, network_proxy: None, diff --git a/codex-rs/core/src/tools/registry.rs b/codex-rs/core/src/tools/registry.rs index 0918fe1aaa..a1bb741b1b 100644 --- a/codex-rs/core/src/tools/registry.rs +++ b/codex-rs/core/src/tools/registry.rs @@ -409,15 +409,15 @@ impl ToolRegistry { ( "sandbox", permission_profile_sandbox_tag( - &invocation.turn.permission_profile, - invocation.turn.windows_sandbox_level, + &invocation.turn.permission_profile(), + invocation.turn.windows_sandbox_level(), invocation.turn.network.is_some(), ), ), ( "sandbox_policy", permission_profile_policy_tag( - &invocation.turn.permission_profile, + &invocation.turn.permission_profile(), #[allow(deprecated)] invocation.turn.cwd.as_path(), ), diff --git a/codex-rs/core/src/tools/runtimes/apply_patch.rs b/codex-rs/core/src/tools/runtimes/apply_patch.rs index 2573f4f821..6e9ed3c528 100644 --- a/codex-rs/core/src/tools/runtimes/apply_patch.rs +++ b/codex-rs/core/src/tools/runtimes/apply_patch.rs @@ -210,8 +210,8 @@ impl Approvable for ApplyPatchRuntime { } impl ToolRuntime for ApplyPatchRuntime { - fn workspace_roots<'a>(&self, req: &'a ApplyPatchRequest) -> &'a [PathUri] { - req.turn_environment.workspace_roots() + fn turn_environment<'a>(&'a self, req: &'a ApplyPatchRequest) -> &'a TurnEnvironment { + &req.turn_environment } fn sandbox_cwd<'a>(&self, req: &'a ApplyPatchRequest) -> Option<&'a PathUri> { diff --git a/codex-rs/core/src/tools/runtimes/shell.rs b/codex-rs/core/src/tools/runtimes/shell.rs index 1d25672e92..d3befc0134 100644 --- a/codex-rs/core/src/tools/runtimes/shell.rs +++ b/codex-rs/core/src/tools/runtimes/shell.rs @@ -210,8 +210,8 @@ impl Approvable for ShellRuntime { } impl ToolRuntime for ShellRuntime { - fn workspace_roots<'a>(&self, req: &'a ShellRequest) -> &'a [PathUri] { - req.turn_environment.workspace_roots() + fn turn_environment<'a>(&'a self, req: &'a ShellRequest) -> &'a TurnEnvironment { + &req.turn_environment } fn network_approval_spec( @@ -219,7 +219,7 @@ impl ToolRuntime for ShellRuntime { req: &ShellRequest, ctx: &ToolCtx, ) -> Option { - let file_system_sandbox_policy = ctx.turn.file_system_sandbox_policy(); + let file_system_sandbox_policy = req.turn_environment.file_system_sandbox_policy(); let sandbox_permissions = sandbox_permissions_preserving_denied_reads( req.sandbox_permissions, &file_system_sandbox_policy, diff --git a/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs b/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs index 42ffd3e9aa..01b7541c6d 100644 --- a/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs +++ b/codex-rs/core/src/tools/runtimes/shell/unix_escalation.rs @@ -202,7 +202,7 @@ pub(super) async fn try_run_zsh_fork( sandbox_policy_cwd, windows_sandbox_workspace_roots, codex_linux_sandbox_exe: ctx.turn.config.codex_linux_sandbox_exe.clone(), - use_legacy_landlock: ctx.turn.config.features.use_legacy_landlock(), + use_legacy_landlock: req.turn_environment.settings.sandbox.use_legacy_landlock, }; let main_execve_wrapper_exe = ctx .session @@ -241,6 +241,7 @@ pub(super) async fn try_run_zsh_fork( environment_id: req.turn_environment.environment_id.clone(), tool_name: GuardianCommandSource::Shell, approval_policy: ctx.turn.approval_policy.value(), + windows_sandbox_level: req.turn_environment.settings.sandbox.windows_sandbox_level, permission_profile: command_executor.permission_profile.clone(), file_system_sandbox_policy: command_executor.file_system_sandbox_policy.clone(), sandbox_permissions: req.sandbox_permissions, @@ -315,7 +316,7 @@ pub(crate) async fn prepare_unified_exec_zsh_fork( sandbox_policy_cwd, windows_sandbox_workspace_roots: exec_request.windows_sandbox_workspace_roots.clone(), codex_linux_sandbox_exe: ctx.turn.config.codex_linux_sandbox_exe.clone(), - use_legacy_landlock: ctx.turn.config.features.use_legacy_landlock(), + use_legacy_landlock: req.turn_environment.settings.sandbox.use_legacy_landlock, }; let escalation_policy = CoreShellActionProvider { policy: Arc::clone(&exec_policy), @@ -325,6 +326,7 @@ pub(crate) async fn prepare_unified_exec_zsh_fork( environment_id: req.turn_environment.environment_id.clone(), tool_name: GuardianCommandSource::UnifiedExec, approval_policy: ctx.turn.approval_policy.value(), + windows_sandbox_level: req.turn_environment.settings.sandbox.windows_sandbox_level, permission_profile: exec_request.permission_profile.clone(), file_system_sandbox_policy: exec_request.file_system_sandbox_policy.clone(), sandbox_permissions: req.sandbox_permissions, @@ -360,6 +362,7 @@ struct CoreShellActionProvider { environment_id: String, tool_name: GuardianCommandSource, approval_policy: AskForApproval, + windows_sandbox_level: WindowsSandboxLevel, permission_profile: PermissionProfile, file_system_sandbox_policy: FileSystemSandboxPolicy, sandbox_permissions: SandboxPermissions, @@ -652,7 +655,7 @@ impl CoreShellActionProvider { InterceptedExecPolicyContext { approval_policy: self.approval_policy, permission_profile: self.permission_profile.clone(), - windows_sandbox_level: self.turn.windows_sandbox_level, + windows_sandbox_level: self.windows_sandbox_level, sandbox_permissions: self.approval_sandbox_permissions, enable_shell_wrapper_parsing: ENABLE_INTERCEPTED_EXEC_POLICY_SHELL_WRAPPER_PARSING, diff --git a/codex-rs/core/src/tools/runtimes/shell/unix_escalation_tests.rs b/codex-rs/core/src/tools/runtimes/shell/unix_escalation_tests.rs index 5478c1d946..77c4a8c20a 100644 --- a/codex-rs/core/src/tools/runtimes/shell/unix_escalation_tests.rs +++ b/codex-rs/core/src/tools/runtimes/shell/unix_escalation_tests.rs @@ -429,6 +429,7 @@ async fn preapproved_additional_permissions_escalate_intercepted_exec() -> anyho environment_id: "local".to_string(), tool_name: GuardianCommandSource::Shell, approval_policy: AskForApproval::OnRequest, + windows_sandbox_level: WindowsSandboxLevel::Disabled, permission_profile: permission_profile.clone(), file_system_sandbox_policy: read_only_file_system_sandbox_policy(), sandbox_permissions: SandboxPermissions::WithAdditionalPermissions, @@ -547,10 +548,10 @@ async fn execve_permission_request_hook_short_circuits_prompt() -> anyhow::Resul }))); turn_context.approval_policy = Constrained::allow_any(AskForApproval::OnRequest); - turn_context.permission_profile = PermissionProfile::from_runtime_permissions( + turn_context.set_permission_profile_for_tests(PermissionProfile::from_runtime_permissions( &read_only_file_system_sandbox_policy(), NetworkSandboxPolicy::Restricted, - ); + )); let workdir = AbsolutePathBuf::try_from(std::env::current_dir()?)?; let target = std::env::temp_dir().join("execve-hook-short-circuit.txt"); let target_str = target.display().to_string(); @@ -565,6 +566,7 @@ async fn execve_permission_request_hook_short_circuits_prompt() -> anyhow::Resul environment_id: "local".to_string(), tool_name: GuardianCommandSource::Shell, approval_policy: AskForApproval::OnRequest, + windows_sandbox_level: WindowsSandboxLevel::Disabled, permission_profile: PermissionProfile::read_only(), file_system_sandbox_policy: read_only_file_system_sandbox_policy(), sandbox_permissions: SandboxPermissions::RequireEscalated, @@ -776,6 +778,7 @@ prefix_rule(pattern = ["{cat_path_literal}"], decision = "allow") environment_id: "local".to_string(), tool_name: GuardianCommandSource::Shell, approval_policy: AskForApproval::OnRequest, + windows_sandbox_level: WindowsSandboxLevel::Disabled, permission_profile, file_system_sandbox_policy, sandbox_permissions: SandboxPermissions::UseDefault, @@ -819,6 +822,7 @@ async fn denied_reads_keep_granular_sandbox_rejection_for_escalation() -> anyhow request_permissions: true, mcp_elicitations: true, }), + windows_sandbox_level: WindowsSandboxLevel::Disabled, permission_profile, file_system_sandbox_policy, sandbox_permissions: SandboxPermissions::RequireEscalated, diff --git a/codex-rs/core/src/tools/runtimes/unified_exec.rs b/codex-rs/core/src/tools/runtimes/unified_exec.rs index 5dcb394956..ae5b8d1357 100644 --- a/codex-rs/core/src/tools/runtimes/unified_exec.rs +++ b/codex-rs/core/src/tools/runtimes/unified_exec.rs @@ -256,8 +256,8 @@ impl Approvable for UnifiedExecRuntime<'_> { } impl<'a> ToolRuntime for UnifiedExecRuntime<'a> { - fn workspace_roots<'b>(&self, req: &'b UnifiedExecRequest) -> &'b [PathUri] { - req.turn_environment.workspace_roots() + fn turn_environment<'b>(&'b self, req: &'b UnifiedExecRequest) -> &'b TurnEnvironment { + &req.turn_environment } fn sandbox_cwd<'b>(&self, req: &'b UnifiedExecRequest) -> Option<&'b PathUri> { @@ -269,7 +269,7 @@ impl<'a> ToolRuntime for UnifiedExecRunt req: &UnifiedExecRequest, ctx: &ToolCtx, ) -> Option { - let file_system_sandbox_policy = ctx.turn.file_system_sandbox_policy(); + let file_system_sandbox_policy = req.turn_environment.file_system_sandbox_policy(); let sandbox_permissions = sandbox_permissions_preserving_denied_reads( req.sandbox_permissions, &file_system_sandbox_policy, diff --git a/codex-rs/core/src/tools/sandboxing.rs b/codex-rs/core/src/tools/sandboxing.rs index 56587a27d2..2437ee820b 100644 --- a/codex-rs/core/src/tools/sandboxing.rs +++ b/codex-rs/core/src/tools/sandboxing.rs @@ -387,7 +387,10 @@ pub(crate) enum ToolError { } pub(crate) trait ToolRuntime: Approvable + Sandboxable { - fn workspace_roots<'a>(&self, req: &'a Req) -> &'a [PathUri]; + fn turn_environment<'a>( + &'a self, + req: &'a Req, + ) -> &'a crate::session::turn_context::TurnEnvironment; fn network_approval_spec(&self, _req: &Req, _ctx: &ToolCtx) -> Option { None diff --git a/codex-rs/core/src/tools/spec_plan.rs b/codex-rs/core/src/tools/spec_plan.rs index 570106764e..24afab8c77 100644 --- a/codex-rs/core/src/tools/spec_plan.rs +++ b/codex-rs/core/src/tools/spec_plan.rs @@ -588,7 +588,7 @@ fn add_tool_sources(context: &CoreToolPlanContext<'_>, planned_tools: &mut Plann if environment_mode.has_environment() { let include_environment_id = matches!(environment_mode, ToolEnvironmentMode::Multiple); planned_tools.add(ExecCommandHandler::new(ExecCommandHandlerOptions { - allow_login_shell: turn_context.config.permissions.allow_login_shell, + allow_login_shell: environments_allow_login_shell(context.step_context), exec_permission_approvals_enabled: false, include_environment_id, include_shell_parameter: unified_exec_should_include_shell_parameter( @@ -635,6 +635,13 @@ fn tool_environment_mode(step_context: &StepContext) -> ToolEnvironmentMode { ToolEnvironmentMode::from_count(step_context.environments.turn_environments().count()) } +fn environments_allow_login_shell(step_context: &StepContext) -> bool { + step_context + .environments + .turn_environments() + .any(|environment| environment.settings.allow_login_shell) +} + #[instrument(level = "trace", skip_all)] fn add_shell_tools(context: &CoreToolPlanContext<'_>, planned_tools: &mut PlannedTools) { let turn_context = context.step_context.turn.as_ref(); @@ -644,7 +651,7 @@ fn add_shell_tools(context: &CoreToolPlanContext<'_>, planned_tools: &mut Planne return; } - let allow_login_shell = turn_context.config.permissions.allow_login_shell; + let allow_login_shell = environments_allow_login_shell(context.step_context); let exec_permission_approvals_enabled = features.enabled(Feature::ExecPermissionApprovals); let include_environment_id = matches!(environment_mode, ToolEnvironmentMode::Multiple); let shell_command_options = ShellCommandHandlerOptions { diff --git a/codex-rs/core/src/unified_exec/mod_tests.rs b/codex-rs/core/src/unified_exec/mod_tests.rs index 22c08f4aeb..fc7689c587 100644 --- a/codex-rs/core/src/unified_exec/mod_tests.rs +++ b/codex-rs/core/src/unified_exec/mod_tests.rs @@ -84,7 +84,7 @@ fn test_exec_request( ExecCapturePolicy::ShellTool, SandboxType::None, turn.config.effective_workspace_roots(), - turn.windows_sandbox_level, + turn.windows_sandbox_level(), windows_sandbox_private_desktop, permission_profile, arg0, diff --git a/codex-rs/core/src/unified_exec/process_manager.rs b/codex-rs/core/src/unified_exec/process_manager.rs index d4418ea247..232a60f112 100644 --- a/codex-rs/core/src/unified_exec/process_manager.rs +++ b/codex-rs/core/src/unified_exec/process_manager.rs @@ -1152,8 +1152,9 @@ impl UnifiedExecProcessManager { cwd: PathUri, context: &UnifiedExecContext, ) -> Result<(UnifiedExecProcess, Option), UnifiedExecError> { + let turn_environment = &request.turn_environment; let local_policy_env = create_env( - &context.turn.config.permissions.shell_environment_policy, + &turn_environment.settings.shell_environment_policy, /*thread_id*/ None, ); let mut env = local_policy_env.clone(); @@ -1161,12 +1162,12 @@ impl UnifiedExecProcessManager { CODEX_THREAD_ID_ENV_VAR.to_string(), context.session.thread_id.to_string(), ); - let active_permission_profile = context.turn.config.permissions.active_permission_profile(); + let active_permission_profile = turn_environment.active_permission_profile(); inject_permission_profile_env(&mut env, active_permission_profile.as_ref()); let env = apply_unified_exec_env(env); let exec_server_env_config = ExecServerEnvConfig { policy: exec_env_policy_from_shell_policy( - &context.turn.config.permissions.shell_environment_policy, + &turn_environment.settings.shell_environment_policy, ), local_policy_env, }; @@ -1179,8 +1180,8 @@ impl UnifiedExecProcessManager { .create_exec_approval_requirement_for_command(ExecApprovalRequest { command: &request.command, approval_policy: context.turn.approval_policy.value(), - permission_profile: context.turn.permission_profile(), - windows_sandbox_level: context.turn.windows_sandbox_level, + permission_profile: turn_environment.permission_profile().clone(), + windows_sandbox_level: turn_environment.settings.sandbox.windows_sandbox_level, sandbox_permissions: if request.additional_permissions_preapproved { crate::sandboxing::SandboxPermissions::UseDefault } else { @@ -1199,10 +1200,8 @@ impl UnifiedExecProcessManager { turn_environment: request.turn_environment.clone(), env, exec_server_env_config: Some(exec_server_env_config), - explicit_env_overrides: context - .turn - .config - .permissions + explicit_env_overrides: turn_environment + .settings .shell_environment_policy .r#set .clone(), diff --git a/codex-rs/core/tests/common/test_codex.rs b/codex-rs/core/tests/common/test_codex.rs index d9e00df96a..677e74526d 100644 --- a/codex-rs/core/tests/common/test_codex.rs +++ b/codex-rs/core/tests/common/test_codex.rs @@ -111,6 +111,7 @@ pub fn local(cwd: AbsolutePathBuf) -> TurnEnvironmentSelection { environment_id: codex_exec_server::LOCAL_ENVIRONMENT_ID.to_string(), cwd: PathUri::from_abs_path(&cwd), workspace_roots: vec![PathUri::from_abs_path(&cwd)], + sandbox: None, } } @@ -143,6 +144,7 @@ impl TestEnv { environment_id: codex_exec_server::REMOTE_ENVIRONMENT_ID.to_string(), cwd: PathUri::from_abs_path(&cwd), workspace_roots: vec![PathUri::from_abs_path(&cwd)], + sandbox: None, }, None => local(cwd.clone()), }; @@ -211,6 +213,7 @@ pub async fn test_env() -> Result { environment_id: codex_exec_server::REMOTE_ENVIRONMENT_ID.to_string(), cwd: cwd_uri.clone(), workspace_roots: vec![cwd_uri.clone()], + sandbox: None, }; let cwd = if remote_env == TestEnvironment::WineExec { // TODO(anp): Convert `Config::cwd` to `LegacyAppPathString` and remove this diff --git a/codex-rs/core/tests/suite/agents_md.rs b/codex-rs/core/tests/suite/agents_md.rs index 65c377e321..2e66339c51 100644 --- a/codex-rs/core/tests/suite/agents_md.rs +++ b/codex-rs/core/tests/suite/agents_md.rs @@ -706,11 +706,13 @@ async fn multi_environment_thread_loads_every_project_and_keeps_creation_snapsho environment_id: REMOTE_ENVIRONMENT_ID.to_string(), cwd: PathUri::from_abs_path(&test.config.cwd), workspace_roots: vec![PathUri::from_abs_path(&test.config.cwd)], + sandbox: None, }, TurnEnvironmentSelection { environment_id: LOCAL_ENVIRONMENT_ID.to_string(), cwd: PathUri::from_host_native_path(local_root.path())?, workspace_roots: vec![PathUri::from_host_native_path(local_root.path())?], + sandbox: None, }, ], thread_extension_init: Default::default(), diff --git a/codex-rs/core/tests/suite/apply_patch_cli.rs b/codex-rs/core/tests/suite/apply_patch_cli.rs index 51ea0421ea..85c33bf428 100644 --- a/codex-rs/core/tests/suite/apply_patch_cli.rs +++ b/codex-rs/core/tests/suite/apply_patch_cli.rs @@ -1654,6 +1654,7 @@ async fn apply_patch_turn_diff_tracks_local_and_remote_environment_paths() -> Re environment_id: REMOTE_ENVIRONMENT_ID.to_string(), cwd: PathUri::from_abs_path(&shared_cwd), workspace_roots: vec![PathUri::from_abs_path(&shared_cwd)], + sandbox: None, }, ]; test.codex diff --git a/codex-rs/core/tests/suite/model_visible_layout.rs b/codex-rs/core/tests/suite/model_visible_layout.rs index 44b7c9b098..b7dbcbd3f3 100644 --- a/codex-rs/core/tests/suite/model_visible_layout.rs +++ b/codex-rs/core/tests/suite/model_visible_layout.rs @@ -115,6 +115,7 @@ async fn model_visible_environment_context_preserves_foreign_workspace_roots() - environment_id: LOCAL_ENVIRONMENT_ID.to_string(), cwd: PathUri::from_abs_path(&test.config.cwd), workspace_roots: vec![foreign_root], + sandbox: None, }], )), ..Default::default() diff --git a/codex-rs/core/tests/suite/multi_exec_server_sandbox.rs b/codex-rs/core/tests/suite/multi_exec_server_sandbox.rs index 8cd40328c9..ee7290201d 100644 --- a/codex-rs/core/tests/suite/multi_exec_server_sandbox.rs +++ b/codex-rs/core/tests/suite/multi_exec_server_sandbox.rs @@ -11,6 +11,7 @@ use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::Op; use codex_protocol::protocol::ThreadSettingsOverrides; +use codex_protocol::protocol::TurnEnvironmentSandbox; use codex_protocol::protocol::TurnEnvironmentSelection; use codex_protocol::protocol::TurnEnvironmentSelections; use codex_protocol::user_input::UserInput; @@ -185,24 +186,35 @@ async fn two_exec_servers_isolate_workspace_write_roots() -> Result<()> { let first_workspace_uri = PathUri::from_host_native_path(first_workspace.path())?; let second_workspace_uri = PathUri::from_host_native_path(second_workspace.path())?; + let environment_sandbox = TurnEnvironmentSandbox { + permission_profile: PermissionProfile::workspace_write_with( + &[], + NetworkSandboxPolicy::Restricted, + /*exclude_tmpdir_env_var*/ true, + /*exclude_slash_tmp*/ true, + ), + active_permission_profile: None, + windows_sandbox_level: Default::default(), + windows_sandbox_private_desktop: false, + use_legacy_landlock: false, + }; let environments = vec![ TurnEnvironmentSelection { environment_id: FIRST_ENVIRONMENT_ID.to_string(), cwd: first_workspace_uri.clone(), workspace_roots: vec![first_workspace_uri], + sandbox: Some(environment_sandbox.clone()), }, TurnEnvironmentSelection { environment_id: SECOND_ENVIRONMENT_ID.to_string(), cwd: second_workspace_uri.clone(), workspace_roots: vec![second_workspace_uri], + sandbox: Some(environment_sandbox), }, ]; - let permission_profile = PermissionProfile::workspace_write_with( - &[], - NetworkSandboxPolicy::Restricted, - /*exclude_tmpdir_env_var*/ true, - /*exclude_slash_tmp*/ true, - ); + // Keep the thread default unrestricted. This makes the cross-write + // assertions prove that execution used each environment's sandbox. + let permission_profile = PermissionProfile::Disabled; let (sandbox_policy, permission_profile) = turn_permission_fields(permission_profile, test.config.cwd.as_path()); test.codex diff --git a/codex-rs/core/tests/suite/network_approval.rs b/codex-rs/core/tests/suite/network_approval.rs index 56656d7199..5b37a7ff3f 100644 --- a/codex-rs/core/tests/suite/network_approval.rs +++ b/codex-rs/core/tests/suite/network_approval.rs @@ -1068,6 +1068,7 @@ async fn approved_network_host_for_one_environment_still_prompts_in_another() -> environment_id: REMOTE_ENVIRONMENT_ID.to_string(), cwd: PathUri::from_abs_path(&remote_cwd), workspace_roots: vec![PathUri::from_abs_path(&remote_cwd)], + sandbox: None, }, ]; diff --git a/codex-rs/core/tests/suite/remote_env.rs b/codex-rs/core/tests/suite/remote_env.rs index 3d62201514..853c39483a 100644 --- a/codex-rs/core/tests/suite/remote_env.rs +++ b/codex-rs/core/tests/suite/remote_env.rs @@ -319,6 +319,7 @@ async fn explicit_remote_shell_runs_in_remote_cwd() -> Result<()> { environment_id: REMOTE_ENVIRONMENT_ID.to_string(), cwd: PathUri::from_abs_path(&test.config.cwd), workspace_roots: vec![PathUri::from_abs_path(&test.config.cwd)], + sandbox: None, }]), ) .await?; @@ -708,6 +709,7 @@ async fn deferred_executor_starts_noise_connection_after_registration() -> Resul environment_id: REMOTE_ENVIRONMENT_ID.to_string(), cwd: PathUri::from_abs_path(&test.config.cwd), workspace_roots: vec![PathUri::from_abs_path(&test.config.cwd)], + sandbox: None, }], )), ..Default::default() @@ -902,6 +904,7 @@ async fn deferred_executor_wait_reports_startup_failure() -> Result<()> { environment_id: REMOTE_ENVIRONMENT_ID.to_string(), cwd: PathUri::from_abs_path(&test.config.cwd), workspace_roots: vec![PathUri::from_abs_path(&test.config.cwd)], + sandbox: None, }], )), ..Default::default() @@ -1251,6 +1254,7 @@ async fn exec_command_routes_to_selected_remote_environment() -> Result<()> { environment_id: REMOTE_ENVIRONMENT_ID.to_string(), cwd: PathUri::from_abs_path(&remote_cwd), workspace_roots: vec![PathUri::from_abs_path(&remote_cwd)], + sandbox: None, }; let multi_env_output = exec_command_routing_output( &test, @@ -1390,11 +1394,13 @@ async fn remote_exec_materializes_target_roots_before_sandbox_selection() -> Res environment_id: LOCAL_ENVIRONMENT_ID.to_string(), cwd: PathUri::from_abs_path(&local_cwd.path().abs()), workspace_roots: Vec::new(), + sandbox: None, }, TurnEnvironmentSelection { environment_id: REMOTE_ENVIRONMENT_ID.to_string(), cwd: remote_cwd_uri.clone(), workspace_roots: vec![remote_cwd_uri.clone()], + sandbox: None, }, ], )), @@ -1563,6 +1569,7 @@ async fn remote_request_permissions_grant_unblocks_later_remote_exec() -> Result environment_id: REMOTE_ENVIRONMENT_ID.to_string(), cwd: PathUri::from_abs_path(&remote_cwd), workspace_roots: vec![PathUri::from_abs_path(&remote_cwd)], + sandbox: None, }, ], AskForApproval::OnRequest, @@ -1705,6 +1712,7 @@ async fn apply_patch_freeform_routes_to_selected_remote_environment() -> Result< environment_id: REMOTE_ENVIRONMENT_ID.to_string(), cwd: PathUri::from_abs_path(&remote_cwd), workspace_roots: vec![PathUri::from_abs_path(&remote_cwd)], + sandbox: None, }, ]), ) @@ -1789,6 +1797,7 @@ async fn apply_patch_approvals_are_remembered_per_environment() -> Result<()> { environment_id: REMOTE_ENVIRONMENT_ID.to_string(), cwd: PathUri::from_abs_path(&remote_cwd), workspace_roots: vec![PathUri::from_abs_path(&remote_cwd)], + sandbox: None, }, ]; let local_patch = format!( @@ -1991,6 +2000,7 @@ async fn apply_patch_intercepted_exec_command_routes_to_selected_remote_environm environment_id: REMOTE_ENVIRONMENT_ID.to_string(), cwd: PathUri::from_abs_path(&remote_cwd), workspace_roots: vec![PathUri::from_abs_path(&remote_cwd)], + sandbox: None, }, ]), ) diff --git a/codex-rs/core/tests/suite/resume_warning.rs b/codex-rs/core/tests/suite/resume_warning.rs index 6cd3e8f452..6a6e96bf2b 100644 --- a/codex-rs/core/tests/suite/resume_warning.rs +++ b/codex-rs/core/tests/suite/resume_warning.rs @@ -39,6 +39,7 @@ fn resume_history( permission_profile: None, network: None, file_system_sandbox_policy: None, + environment_sandboxes: None, model: previous_model.to_string(), comp_hash: None, personality: None, diff --git a/codex-rs/core/tests/suite/view_image.rs b/codex-rs/core/tests/suite/view_image.rs index ab567f9845..cf82d87901 100644 --- a/codex-rs/core/tests/suite/view_image.rs +++ b/codex-rs/core/tests/suite/view_image.rs @@ -587,6 +587,7 @@ async fn view_image_routes_to_selected_remote_environment() -> anyhow::Result<() environment_id: REMOTE_ENVIRONMENT_ID.to_string(), cwd: remote_cwd_uri.clone(), workspace_roots: vec![remote_cwd_uri], + sandbox: None, }; let relative_call_id = "call-view-image-relative-multi-env"; let absolute_call_id = "call-view-image-absolute-multi-env"; diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 292326a4e0..cb894d7d45 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -138,6 +138,36 @@ pub struct TurnEnvironmentSelection { pub environment_id: String, pub cwd: PathUri, pub workspace_roots: Vec, + pub sandbox: Option, +} + +/// Sandbox settings captured for one selected environment. +/// +/// These settings travel with [`TurnEnvironmentSelection`] so environment +/// forwarding cannot silently drop its sandbox. +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, JsonSchema, TS)] +pub struct TurnEnvironmentSandbox { + pub permission_profile: PermissionProfile, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub active_permission_profile: Option, + pub windows_sandbox_level: WindowsSandboxLevel, + #[serde(default)] + pub windows_sandbox_private_desktop: bool, + #[serde(default)] + pub use_legacy_landlock: bool, +} + +impl Default for TurnEnvironmentSandbox { + fn default() -> Self { + Self { + permission_profile: PermissionProfile::default(), + active_permission_profile: None, + windows_sandbox_level: WindowsSandboxLevel::Disabled, + windows_sandbox_private_desktop: false, + use_legacy_landlock: false, + } + } } #[derive(Debug, Clone, PartialEq)] @@ -3307,6 +3337,10 @@ pub struct TurnContextItem { pub network: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub file_system_sandbox_policy: Option, + /// Explicit sandbox overrides captured for selected environments. Older + /// rollout items omit this and inherit the top-level permission fields. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub environment_sandboxes: Option>, pub model: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub comp_hash: Option, diff --git a/codex-rs/rollout/src/recorder_tests.rs b/codex-rs/rollout/src/recorder_tests.rs index 0eba013d5b..324ce7c15b 100644 --- a/codex-rs/rollout/src/recorder_tests.rs +++ b/codex-rs/rollout/src/recorder_tests.rs @@ -1510,6 +1510,7 @@ async fn resume_candidate_matches_cwd_reads_latest_turn_context() -> std::io::Re permission_profile: None, network: None, file_system_sandbox_policy: None, + environment_sandboxes: None, model: "test-model".to_string(), comp_hash: None, personality: None, diff --git a/codex-rs/state/src/extract.rs b/codex-rs/state/src/extract.rs index 06dfff5a73..5091516fb0 100644 --- a/codex-rs/state/src/extract.rs +++ b/codex-rs/state/src/extract.rs @@ -430,6 +430,7 @@ mod tests { permission_profile: None, network: None, file_system_sandbox_policy: None, + environment_sandboxes: None, model: "gpt-5".to_string(), comp_hash: None, personality: None, @@ -476,6 +477,7 @@ mod tests { permission_profile: Some(permission_profile.clone()), network: None, file_system_sandbox_policy: None, + environment_sandboxes: None, model: "gpt-5".to_string(), comp_hash: None, personality: None, @@ -518,6 +520,7 @@ mod tests { permission_profile: None, network: None, file_system_sandbox_policy: None, + environment_sandboxes: None, model: "gpt-5".to_string(), comp_hash: None, personality: None, @@ -557,6 +560,7 @@ mod tests { permission_profile: None, network: None, file_system_sandbox_policy: None, + environment_sandboxes: None, model: "gpt-5".to_string(), comp_hash: None, personality: None, diff --git a/codex-rs/thread-store/src/local/mod.rs b/codex-rs/thread-store/src/local/mod.rs index f0f8adbec6..7188cc5076 100644 --- a/codex-rs/thread-store/src/local/mod.rs +++ b/codex-rs/thread-store/src/local/mod.rs @@ -584,6 +584,7 @@ mod tests { permission_profile: None, network: None, file_system_sandbox_policy: None, + environment_sandboxes: None, model: model.to_string(), comp_hash: None, personality: None, diff --git a/codex-rs/thread-store/src/local/model_context_tests.rs b/codex-rs/thread-store/src/local/model_context_tests.rs index 89a7c0bdaf..c2a5776e4e 100644 --- a/codex-rs/thread-store/src/local/model_context_tests.rs +++ b/codex-rs/thread-store/src/local/model_context_tests.rs @@ -374,6 +374,7 @@ fn turn_context(root: &Path, turn_id: &str) -> RolloutItem { permission_profile: None, network: None, file_system_sandbox_policy: None, + environment_sandboxes: None, model: "test-model".to_string(), comp_hash: None, personality: None,