Support keyed shell environment requirements

This commit is contained in:
Abhinav Vedmala
2026-06-15 20:54:38 +00:00
parent 5e8d468b44
commit addd8f375d
21 changed files with 775 additions and 38 deletions
@@ -8348,6 +8348,14 @@
"description": "Lossless config-native OTEL requirements, including exporter headers."
},
"shellEnvironmentPolicy": {
"anyOf": [
{
"$ref": "#/definitions/v2/ShellEnvironmentPolicyRequirements"
},
{
"type": "null"
}
],
"description": "Lossless config-native shell environment policy requirements."
},
"sqliteHome": {
@@ -15537,6 +15545,85 @@
],
"type": "object"
},
"ShellEnvironmentPolicyInherit": {
"oneOf": [
{
"description": "\"Core\" environment variables for the platform. On UNIX, this would include HOME, LOGNAME, PATH, SHELL, and USER, among others.",
"enum": [
"core"
],
"type": "string"
},
{
"description": "Inherits the full environment from the parent process.",
"enum": [
"all"
],
"type": "string"
},
{
"description": "Do not inherit any environment variables from the parent process.",
"enum": [
"none"
],
"type": "string"
}
]
},
"ShellEnvironmentPolicyRequirements": {
"properties": {
"exclude": {
"additionalProperties": {
"type": "boolean"
},
"type": [
"object",
"null"
]
},
"experimental_use_profile": {
"type": [
"boolean",
"null"
]
},
"ignore_default_excludes": {
"type": [
"boolean",
"null"
]
},
"include_only": {
"additionalProperties": {
"type": "boolean"
},
"type": [
"object",
"null"
]
},
"inherit": {
"anyOf": [
{
"$ref": "#/definitions/v2/ShellEnvironmentPolicyInherit"
},
{
"type": "null"
}
]
},
"set": {
"additionalProperties": {
"type": "string"
},
"type": [
"object",
"null"
]
}
},
"type": "object"
},
"SkillDependencies": {
"properties": {
"tools": {
@@ -4661,6 +4661,14 @@
"description": "Lossless config-native OTEL requirements, including exporter headers."
},
"shellEnvironmentPolicy": {
"anyOf": [
{
"$ref": "#/definitions/ShellEnvironmentPolicyRequirements"
},
{
"type": "null"
}
],
"description": "Lossless config-native shell environment policy requirements."
},
"sqliteHome": {
@@ -13345,6 +13353,85 @@
],
"type": "object"
},
"ShellEnvironmentPolicyInherit": {
"oneOf": [
{
"description": "\"Core\" environment variables for the platform. On UNIX, this would include HOME, LOGNAME, PATH, SHELL, and USER, among others.",
"enum": [
"core"
],
"type": "string"
},
{
"description": "Inherits the full environment from the parent process.",
"enum": [
"all"
],
"type": "string"
},
{
"description": "Do not inherit any environment variables from the parent process.",
"enum": [
"none"
],
"type": "string"
}
]
},
"ShellEnvironmentPolicyRequirements": {
"properties": {
"exclude": {
"additionalProperties": {
"type": "boolean"
},
"type": [
"object",
"null"
]
},
"experimental_use_profile": {
"type": [
"boolean",
"null"
]
},
"ignore_default_excludes": {
"type": [
"boolean",
"null"
]
},
"include_only": {
"additionalProperties": {
"type": "boolean"
},
"type": [
"object",
"null"
]
},
"inherit": {
"anyOf": [
{
"$ref": "#/definitions/ShellEnvironmentPolicyInherit"
},
{
"type": "null"
}
]
},
"set": {
"additionalProperties": {
"type": "string"
},
"type": [
"object",
"null"
]
}
},
"type": "object"
},
"SkillDependencies": {
"properties": {
"tools": {
@@ -288,6 +288,14 @@
"description": "Lossless config-native OTEL requirements, including exporter headers."
},
"shellEnvironmentPolicy": {
"anyOf": [
{
"$ref": "#/definitions/ShellEnvironmentPolicyRequirements"
},
{
"type": "null"
}
],
"description": "Lossless config-native shell environment policy requirements."
},
"sqliteHome": {
@@ -645,6 +653,85 @@
],
"type": "string"
},
"ShellEnvironmentPolicyInherit": {
"oneOf": [
{
"description": "\"Core\" environment variables for the platform. On UNIX, this would include HOME, LOGNAME, PATH, SHELL, and USER, among others.",
"enum": [
"core"
],
"type": "string"
},
{
"description": "Inherits the full environment from the parent process.",
"enum": [
"all"
],
"type": "string"
},
{
"description": "Do not inherit any environment variables from the parent process.",
"enum": [
"none"
],
"type": "string"
}
]
},
"ShellEnvironmentPolicyRequirements": {
"properties": {
"exclude": {
"additionalProperties": {
"type": "boolean"
},
"type": [
"object",
"null"
]
},
"experimental_use_profile": {
"type": [
"boolean",
"null"
]
},
"ignore_default_excludes": {
"type": [
"boolean",
"null"
]
},
"include_only": {
"additionalProperties": {
"type": "boolean"
},
"type": [
"object",
"null"
]
},
"inherit": {
"anyOf": [
{
"$ref": "#/definitions/ShellEnvironmentPolicyInherit"
},
{
"type": "null"
}
]
},
"set": {
"additionalProperties": {
"type": "string"
},
"type": [
"object",
"null"
]
}
},
"type": "object"
},
"WebSearchMode": {
"enum": [
"disabled",
@@ -10,6 +10,7 @@ import type { ComputerUseRequirements } from "./ComputerUseRequirements";
import type { FeedbackRequirements } from "./FeedbackRequirements";
import type { ResidencyRequirement } from "./ResidencyRequirement";
import type { SandboxMode } from "./SandboxMode";
import type { ShellEnvironmentPolicyRequirements } from "./ShellEnvironmentPolicyRequirements";
import type { WindowsSandboxSetupMode } from "./WindowsSandboxSetupMode";
export type ConfigRequirements = {allowedApprovalPolicies: Array<AskForApproval> | null, allowedSandboxModes: Array<SandboxMode> | null, allowedWindowsSandboxImplementations: Array<WindowsSandboxSetupMode> | null, allowedPermissionProfiles: { [key in string]?: boolean } | null, defaultPermissions: string | null, allowedWebSearchModes: Array<WebSearchMode> | null, allowManagedHooksOnly: boolean | null, allowAppshots: boolean | null, allowRemoteControl: boolean | null, computerUse: ComputerUseRequirements | null, featureRequirements: { [key in string]?: boolean } | null, enforceResidency: ResidencyRequirement | null, allowedLoginMethods: { [key in string]?: boolean } | null, allowedChatgptWorkspaces: { [key in string]?: boolean } | null, cliAuthCredentialsStore: AuthCredentialsStoreMode | null, chatgptBaseUrl: string | null, sqliteHome: AbsolutePathBuf | null, logDir: AbsolutePathBuf | null, modelCatalogJson: AbsolutePathBuf | null, checkForUpdateOnStartup: boolean | null, /**
@@ -18,4 +19,4 @@ export type ConfigRequirements = {allowedApprovalPolicies: Array<AskForApproval>
otel: JsonValue | null, allowLoginShell: boolean | null, /**
* Lossless config-native shell environment policy requirements.
*/
shellEnvironmentPolicy: JsonValue | null, feedback: FeedbackRequirements | null, windowsSandboxPrivateDesktop: boolean | null};
shellEnvironmentPolicy: ShellEnvironmentPolicyRequirements | null, feedback: FeedbackRequirements | null, windowsSandboxPrivateDesktop: boolean | null};
@@ -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 ShellEnvironmentPolicyInherit = "core" | "all" | "none";
@@ -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 { ShellEnvironmentPolicyInherit } from "./ShellEnvironmentPolicyInherit";
export type ShellEnvironmentPolicyRequirements = { inherit: ShellEnvironmentPolicyInherit | null, ignore_default_excludes: boolean | null, exclude: { [key in string]?: boolean } | null, set: { [key in string]?: string } | null, include_only: { [key in string]?: boolean } | null, experimental_use_profile: boolean | null, };
@@ -345,6 +345,8 @@ export type { SendAddCreditsNudgeEmailResponse } from "./SendAddCreditsNudgeEmai
export type { ServerRequestResolvedNotification } from "./ServerRequestResolvedNotification";
export type { SessionMigration } from "./SessionMigration";
export type { SessionSource } from "./SessionSource";
export type { ShellEnvironmentPolicyInherit } from "./ShellEnvironmentPolicyInherit";
export type { ShellEnvironmentPolicyRequirements } from "./ShellEnvironmentPolicyRequirements";
export type { SkillDependencies } from "./SkillDependencies";
export type { SkillErrorInfo } from "./SkillErrorInfo";
export type { SkillInterface } from "./SkillInterface";
@@ -8,6 +8,7 @@ pub use codex_protocol::config_types::AuthCredentialsStoreMode;
use codex_protocol::config_types::AutoCompactTokenLimitScope;
use codex_protocol::config_types::ForcedLoginMethod;
use codex_protocol::config_types::ReasoningSummary;
use codex_protocol::config_types::ShellEnvironmentPolicyInherit;
use codex_protocol::config_types::Verbosity;
use codex_protocol::config_types::WebSearchMode;
use codex_protocol::config_types::WebSearchToolConfig;
@@ -405,7 +406,7 @@ pub struct ConfigRequirements {
pub otel: Option<JsonValue>,
pub allow_login_shell: Option<bool>,
/// Lossless config-native shell environment policy requirements.
pub shell_environment_policy: Option<JsonValue>,
pub shell_environment_policy: Option<ShellEnvironmentPolicyRequirements>,
pub feedback: Option<FeedbackRequirements>,
pub windows_sandbox_private_desktop: Option<bool>,
}
@@ -417,6 +418,18 @@ pub struct FeedbackRequirements {
pub enabled: Option<bool>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
#[ts(export_to = "v2/")]
pub struct ShellEnvironmentPolicyRequirements {
pub inherit: Option<ShellEnvironmentPolicyInherit>,
pub ignore_default_excludes: Option<bool>,
pub exclude: Option<BTreeMap<String, bool>>,
pub r#set: Option<HashMap<String, String>>,
pub include_only: Option<BTreeMap<String, bool>>,
pub experimental_use_profile: Option<bool>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
+1 -1
View File
@@ -234,7 +234,7 @@ Example with notification opt-out:
- `externalAgentConfig/import` — apply selected external-agent migration items by passing explicit `migrationItems` with `cwd` (`null` for home) and any plugin/session `details` returned by detect. When a request includes migration items, the server emits `externalAgentConfig/import/completed` once after the full import finishes (immediately after the response when everything completed synchronously, or after background imports finish).
- `config/value/write` — write a single config key/value to the user's config.toml on disk; dotted paths such as `desktop.someKey` use the same generic write surface.
- `config/batchWrite` — apply multiple config edits atomically to the user's config.toml on disk, with optional `reloadUserConfig: true` to hot-reload loaded threads, including multiple `desktop.*` edits.
- `configRequirements/read` — fetch loaded requirements constraints from `requirements.toml` and/or MDM (or `null` if none are configured), including allow-lists (`allowedApprovalPolicies`, `allowedSandboxModes`, `allowedWebSearchModes`, `allowedLoginMethods`, `allowedChatgptWorkspaces`), the layered permission-profile allow map (`allowedPermissionProfiles`), the managed permission-profile default (`defaultPermissions`), lifecycle hook lockdown (`allowManagedHooksOnly`), remote-control policy (`allowRemoteControl`; `false` force-disables remote control while `true` or `null` preserves existing behavior), computer use policy (`computerUse`), pinned feature values (`featureRequirements`), managed lifecycle hooks (`hooks`), `enforceResidency`, `network` constraints such as canonical domain/socket permissions plus `managedAllowedDomainsOnly` and `dangerFullAccessDenylistOnly`, and pinned runtime settings such as credential storage, ChatGPT base URL, state/log/model-catalog paths, update checks, login-shell and environment policy, feedback, Windows private-desktop use, and OTEL configuration. OTEL exporter responses include their complete headers map.
- `configRequirements/read` — fetch loaded requirements constraints from `requirements.toml` and/or MDM (or `null` if none are configured), including allow-lists (`allowedApprovalPolicies`, `allowedSandboxModes`, `allowedWebSearchModes`, `allowedLoginMethods`, `allowedChatgptWorkspaces`), the layered permission-profile allow map (`allowedPermissionProfiles`), the managed permission-profile default (`defaultPermissions`), lifecycle hook lockdown (`allowManagedHooksOnly`), remote-control policy (`allowRemoteControl`; `false` force-disables remote control while `true` or `null` preserves existing behavior), computer use policy (`computerUse`), pinned feature values (`featureRequirements`), managed lifecycle hooks (`hooks`), `enforceResidency`, `network` constraints such as canonical domain/socket permissions plus `managedAllowedDomainsOnly` and `dangerFullAccessDenylistOnly`, and pinned runtime settings such as credential storage, ChatGPT base URL, state/log/model-catalog paths, update checks, login-shell and environment policy, feedback, Windows private-desktop use, and OTEL configuration. Shell environment `exclude` and `include_only` requirements are boolean maps whose `false` entries are preserved as tombstones; OTEL exporter responses include their complete headers map.
### Example: Start or resume a thread
@@ -29,6 +29,7 @@ use codex_app_server_protocol::NetworkDomainPermission;
use codex_app_server_protocol::NetworkRequirements;
use codex_app_server_protocol::NetworkUnixSocketPermission;
use codex_app_server_protocol::SandboxMode;
use codex_app_server_protocol::ShellEnvironmentPolicyRequirements;
use codex_app_server_protocol::WindowsSandboxSetupMode;
use codex_config::ConfigRequirementsToml;
use codex_config::HookEventsToml;
@@ -37,6 +38,7 @@ use codex_config::ManagedHooksRequirementsToml;
use codex_config::MatcherGroup as CoreMatcherGroup;
use codex_config::ResidencyRequirement as CoreResidencyRequirement;
use codex_config::SandboxModeRequirement as CoreSandboxModeRequirement;
use codex_config::ShellEnvironmentPolicyRequirementsToml;
use codex_core::ThreadManager;
use codex_features::canonical_feature_for_key;
use codex_features::feature_for_key;
@@ -394,7 +396,7 @@ fn map_requirements_toml_to_api(requirements: ConfigRequirementsToml) -> ConfigR
allow_login_shell: requirements.allow_login_shell,
shell_environment_policy: requirements
.shell_environment_policy
.map(|policy| json!(policy)),
.map(map_shell_environment_policy_requirements_to_api),
feedback: requirements.feedback.map(|feedback| FeedbackRequirements {
enabled: feedback.enabled,
}),
@@ -402,6 +404,27 @@ fn map_requirements_toml_to_api(requirements: ConfigRequirementsToml) -> ConfigR
}
}
fn map_shell_environment_policy_requirements_to_api(
policy: ShellEnvironmentPolicyRequirementsToml,
) -> ShellEnvironmentPolicyRequirements {
let ShellEnvironmentPolicyRequirementsToml {
inherit,
ignore_default_excludes,
exclude,
r#set,
include_only,
experimental_use_profile,
} = policy;
ShellEnvironmentPolicyRequirements {
inherit,
ignore_default_excludes,
exclude,
r#set,
include_only,
experimental_use_profile,
}
}
fn map_computer_use_requirements_to_api(
computer_use: codex_config::ComputerUseRequirementsToml,
) -> ComputerUseRequirements {
@@ -589,13 +612,16 @@ fn config_write_error(code: ConfigWriteErrorCode, message: impl Into<String>) ->
#[cfg(test)]
mod tests {
use super::map_requirements_toml_to_api;
use codex_app_server_protocol::ShellEnvironmentPolicyRequirements;
use codex_app_server_protocol::WindowsSandboxSetupMode;
use codex_config::ComputerUseRequirementsToml;
use codex_config::ConfigRequirementsToml;
use codex_config::WindowsRequirementsToml;
use codex_protocol::config_types::ShellEnvironmentPolicyInherit;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::collections::BTreeMap;
use std::collections::HashMap;
#[test]
fn requirements_api_includes_allow_managed_hooks_only() {
@@ -708,9 +734,16 @@ team = "codex"
[shell_environment_policy]
inherit = "core"
ignore_default_excludes = false
exclude = ["*SECRET*"]
experimental_use_profile = false
[shell_environment_policy.exclude]
"*OLD*" = false
"*SECRET*" = true
[shell_environment_policy.include_only]
"HOME" = true
"PATH" = false
[shell_environment_policy.set]
MANAGED = "true"
"#,
@@ -727,14 +760,22 @@ MANAGED = "true"
);
assert_eq!(
mapped.shell_environment_policy,
Some(json!({
"inherit": "core",
"ignore_default_excludes": false,
"exclude": ["*SECRET*"],
"set": {"MANAGED": "true"},
"include_only": null,
"experimental_use_profile": false
}))
Some(ShellEnvironmentPolicyRequirements {
inherit: Some(ShellEnvironmentPolicyInherit::Core),
ignore_default_excludes: Some(false),
exclude: Some(BTreeMap::from([
("*OLD*".to_string(), false),
("*SECRET*".to_string(), true),
])),
r#set: Some(HashMap::from([
("MANAGED".to_string(), "true".to_string(),)
])),
include_only: Some(BTreeMap::from([
("HOME".to_string(), true),
("PATH".to_string(), false),
])),
experimental_use_profile: Some(false),
})
);
}
}
+62 -6
View File
@@ -1,5 +1,6 @@
use codex_protocol::config_types::ApprovalsReviewer;
use codex_protocol::config_types::SandboxMode;
use codex_protocol::config_types::ShellEnvironmentPolicyInherit;
use codex_protocol::config_types::WebSearchMode;
use codex_protocol::models::PermissionProfile;
use codex_protocol::protocol::AskForApproval;
@@ -10,6 +11,7 @@ use serde::de::Error as _;
use serde::de::value::Error as ValueDeserializerError;
use serde::de::value::StrDeserializer;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::fmt;
use wildmatch::WildMatchPattern;
@@ -23,7 +25,6 @@ use crate::permissions_toml::PermissionProfileToml;
use crate::types::AuthCredentialsStoreMode;
use crate::types::FeedbackConfigToml;
use crate::types::OtelConfigToml;
use crate::types::ShellEnvironmentPolicyToml;
use crate::types::WindowsSandboxModeToml;
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -156,7 +157,7 @@ pub struct ConfigRequirements {
pub check_for_update_on_startup: Option<Sourced<bool>>,
pub otel: Option<Sourced<OtelConfigToml>>,
pub allow_login_shell: Option<Sourced<bool>>,
pub shell_environment_policy: Option<Sourced<ShellEnvironmentPolicyToml>>,
pub shell_environment_policy: Option<Sourced<ShellEnvironmentPolicyRequirementsToml>>,
pub feedback: Option<Sourced<FeedbackConfigToml>>,
pub approval_policy: ConstrainedWithSource<AskForApproval>,
pub approvals_reviewer: ConstrainedWithSource<ApprovalsReviewer>,
@@ -862,7 +863,7 @@ pub struct ConfigRequirementsToml {
pub check_for_update_on_startup: Option<bool>,
pub otel: Option<OtelConfigToml>,
pub allow_login_shell: Option<bool>,
pub shell_environment_policy: Option<ShellEnvironmentPolicyToml>,
pub shell_environment_policy: Option<ShellEnvironmentPolicyRequirementsToml>,
pub feedback: Option<FeedbackConfigToml>,
pub allowed_approval_policies: Option<Vec<AskForApproval>>,
pub allowed_approvals_reviewers: Option<Vec<ApprovalsReviewer>>,
@@ -890,6 +891,22 @@ pub struct ConfigRequirementsToml {
pub guardian_policy_config: Option<String>,
}
/// Managed shell environment policy fields accepted by `requirements.toml`.
///
/// Unlike ordinary `config.toml`, requirements intentionally accept only
/// boolean maps for list-like fields. This keeps tombstones composable by key
/// while config arrays remain a migration-only compatibility path that can be
/// deprecated independently later.
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
pub struct ShellEnvironmentPolicyRequirementsToml {
pub inherit: Option<ShellEnvironmentPolicyInherit>,
pub ignore_default_excludes: Option<bool>,
pub exclude: Option<BTreeMap<String, bool>>,
pub r#set: Option<HashMap<String, String>>,
pub include_only: Option<BTreeMap<String, bool>>,
pub experimental_use_profile: Option<bool>,
}
#[derive(Deserialize, Debug, Clone, PartialEq)]
pub struct RemoteSandboxConfigToml {
pub hostname_patterns: Vec<String>,
@@ -930,7 +947,7 @@ pub struct ConfigRequirementsWithSources {
pub check_for_update_on_startup: Option<Sourced<bool>>,
pub otel: Option<Sourced<OtelConfigToml>>,
pub allow_login_shell: Option<Sourced<bool>>,
pub shell_environment_policy: Option<Sourced<ShellEnvironmentPolicyToml>>,
pub shell_environment_policy: Option<Sourced<ShellEnvironmentPolicyRequirementsToml>>,
pub feedback: Option<Sourced<FeedbackConfigToml>>,
pub allowed_approval_policies: Option<Sourced<Vec<AskForApproval>>>,
pub allowed_approvals_reviewers: Option<Sourced<Vec<ApprovalsReviewer>>>,
@@ -1222,7 +1239,7 @@ impl ConfigRequirementsToml {
&& self
.shell_environment_policy
.as_ref()
.is_none_or(|policy| policy == &ShellEnvironmentPolicyToml::default())
.is_none_or(|policy| policy == &ShellEnvironmentPolicyRequirementsToml::default())
&& self
.feedback
.as_ref()
@@ -1742,6 +1759,45 @@ mod tests {
Ok(())
}
#[test]
fn shell_environment_policy_requires_boolean_maps_for_list_fields() -> Result<()> {
let requirements: ConfigRequirementsToml = from_str(
r#"
[shell_environment_policy.exclude]
"ADD_*" = true
"REMOVE_*" = false
[shell_environment_policy.include_only]
"HOME" = true
"PATH" = false
"#,
)?;
assert_eq!(
requirements.shell_environment_policy,
Some(ShellEnvironmentPolicyRequirementsToml {
exclude: Some(BTreeMap::from([
("ADD_*".to_string(), true),
("REMOVE_*".to_string(), false),
])),
include_only: Some(BTreeMap::from([
("HOME".to_string(), true),
("PATH".to_string(), false),
])),
..Default::default()
})
);
for field in ["exclude", "include_only"] {
let error = from_str::<ConfigRequirementsToml>(&format!(
"[shell_environment_policy]\n{field} = [\"LEGACY_*\"]\n"
))
.expect_err("requirements.toml arrays should be rejected");
assert!(error.to_string().contains(field));
}
Ok(())
}
#[test]
fn allow_managed_hooks_only_false_is_still_configured() -> Result<()> {
let requirements: ConfigRequirementsToml = from_str(
@@ -1955,7 +2011,7 @@ mod tests {
log_user_prompt: Some(false),
..Default::default()
};
let shell_environment_policy = ShellEnvironmentPolicyToml {
let shell_environment_policy = ShellEnvironmentPolicyRequirementsToml {
ignore_default_excludes: Some(false),
..Default::default()
};
+1
View File
@@ -74,6 +74,7 @@ pub use config_requirements::RemoteSandboxConfigToml;
pub use config_requirements::RequirementSource;
pub use config_requirements::ResidencyRequirement;
pub use config_requirements::SandboxModeRequirement;
pub use config_requirements::ShellEnvironmentPolicyRequirementsToml;
pub use config_requirements::Sourced;
pub use config_requirements::WebSearchModeRequirement;
pub use config_requirements::WindowsRequirementsToml;
+37
View File
@@ -9,6 +9,15 @@ pub fn merge_toml_values(base: &mut TomlValue, overlay: &TomlValue) {
}
fn merge_toml_values_at_path(base: &mut TomlValue, overlay: &TomlValue, path: &mut Vec<String>) {
// Ordinary config temporarily accepts legacy arrays and keyed boolean maps
// for these fields. Promote a lower array only when a map overlays it so
// tombstones can remove individual entries. Keeping this migration rule
// narrow preserves legacy array replacement and makes arrays easy to
// deprecate later without changing the general TOML merge semantics.
if is_shell_environment_pattern_list_path(path) && overlay.is_table() {
promote_string_array_to_bool_map(base);
}
if let TomlValue::Table(overlay_table) = overlay
&& let TomlValue::Table(base_table) = base
{
@@ -34,6 +43,34 @@ fn merge_toml_values_at_path(base: &mut TomlValue, overlay: &TomlValue, path: &m
}
}
fn is_shell_environment_pattern_list_path(path: &[String]) -> bool {
matches!(
path,
[policy, field]
if policy == "shell_environment_policy"
&& (field == "exclude" || field == "include_only")
)
}
fn promote_string_array_to_bool_map(value: &mut TomlValue) {
let TomlValue::Array(items) = value else {
return;
};
let Some(patterns) = items
.iter()
.map(TomlValue::as_str)
.collect::<Option<Vec<_>>>()
else {
return;
};
*value = TomlValue::Table(
patterns
.into_iter()
.map(|pattern| (pattern.to_string(), TomlValue::Boolean(true)))
.collect(),
);
}
fn is_permission_network_domains_path(path: &[String]) -> bool {
matches!(
path,
+113
View File
@@ -1,6 +1,7 @@
use super::*;
use crate::config_toml::ConfigToml;
use crate::types::MemoriesToml;
use crate::types::ShellEnvironmentPolicyToml;
use pretty_assertions::assert_eq;
fn parse_toml(value: &str) -> TomlValue {
@@ -124,3 +125,115 @@ fn merge_toml_values_normalizes_permission_network_domains_before_overlaying() {
);
assert_eq!(base, expected);
}
#[test]
fn shell_environment_policy_legacy_array_overlay_replaces_legacy_array() {
let mut base = parse_toml(
r#"
[shell_environment_policy]
exclude = ["LOW_*", "SHARED_*"]
"#,
);
let overlay = parse_toml(
r#"
[shell_environment_policy]
exclude = ["HIGH_*"]
"#,
);
merge_toml_values(&mut base, &overlay);
assert_eq!(base, overlay);
}
#[test]
fn shell_environment_policy_bool_map_overlay_merges_by_key() {
let mut base = parse_toml(
r#"
[shell_environment_policy.exclude]
"KEEP_*" = true
"REMOVE_*" = true
"#,
);
let overlay = parse_toml(
r#"
[shell_environment_policy.exclude]
"ADD_*" = true
"REMOVE_*" = false
"#,
);
merge_toml_values(&mut base, &overlay);
assert_eq!(
base,
parse_toml(
r#"
[shell_environment_policy.exclude]
"ADD_*" = true
"KEEP_*" = true
"REMOVE_*" = false
"#,
)
);
}
#[test]
fn shell_environment_policy_bool_map_overlay_promotes_lower_legacy_array() {
let mut base = parse_toml(
r#"
[shell_environment_policy]
include_only = ["HOME", "PATH"]
"#,
);
let overlay = parse_toml(
r#"
[shell_environment_policy.include_only]
"PATH" = false
"USER" = true
"#,
);
merge_toml_values(&mut base, &overlay);
assert_eq!(
base,
parse_toml(
r#"
[shell_environment_policy.include_only]
"HOME" = true
"PATH" = false
"USER" = true
"#,
)
);
let config: ConfigToml = base.try_into().expect("merged config should deserialize");
assert_eq!(
config.shell_environment_policy,
ShellEnvironmentPolicyToml {
include_only: Some(vec!["HOME".to_string(), "USER".to_string()]),
..Default::default()
}
);
}
#[test]
fn shell_environment_policy_legacy_array_overlay_replaces_lower_bool_map() {
let mut base = parse_toml(
r#"
[shell_environment_policy.exclude]
"LOW_*" = true
"#,
);
let overlay = parse_toml(
r#"
[shell_environment_policy]
exclude = ["HIGH_*"]
"#,
);
merge_toml_values(&mut base, &overlay);
assert_eq!(base, overlay);
}
@@ -6,6 +6,7 @@ use super::compose_requirements_for_hostname_and_hook_directory;
use crate::ConfigRequirementsToml;
use crate::ConfigRequirementsWithSources;
use crate::RequirementSource;
use crate::ShellEnvironmentPolicyRequirementsToml;
use crate::Sourced;
use codex_protocol::protocol::AskForApproval;
use codex_utils_absolute_path::AbsolutePathBuf;
@@ -346,6 +347,69 @@ api = false
);
}
#[test]
fn shell_environment_pattern_maps_compose_by_key_with_tombstones() {
let high_source = RequirementSource::EnterpriseManaged {
id: "req_high".to_string(),
name: "High".to_string(),
};
let low_source = RequirementSource::EnterpriseManaged {
id: "req_low".to_string(),
name: "Low".to_string(),
};
let composed = compose_requirements_for_hostname(
vec![
RequirementsLayerEntry::from_toml(
low_source.clone(),
r#"
[shell_environment_policy.exclude]
"KEEP_*" = true
"REMOVE_*" = true
[shell_environment_policy.include_only]
"HOME" = true
"PATH" = true
"#,
),
RequirementsLayerEntry::from_toml(
high_source.clone(),
r#"
[shell_environment_policy.exclude]
"ADD_*" = true
"REMOVE_*" = false
[shell_environment_policy.include_only]
"PATH" = false
"USER" = true
"#,
),
],
/*hostname*/ None,
)
.expect("compose requirements")
.expect("requirements present");
assert_eq!(
composed.shell_environment_policy,
Some(Sourced::new(
ShellEnvironmentPolicyRequirementsToml {
exclude: Some(BTreeMap::from([
("ADD_*".to_string(), true),
("KEEP_*".to_string(), true),
("REMOVE_*".to_string(), false),
])),
include_only: Some(BTreeMap::from([
("HOME".to_string(), true),
("PATH".to_string(), false),
("USER".to_string(), true),
])),
..Default::default()
},
RequirementSource::composite([high_source, low_source]),
))
);
}
#[test]
fn otel_exporters_replace_atomically_across_layers() {
let high_source = RequirementSource::EnterpriseManaged {
+47 -2
View File
@@ -913,6 +913,41 @@ impl From<SandboxWorkspaceWrite> for codex_app_server_protocol::SandboxSettings
}
}
// Compatibility input for list-like shell environment policy fields.
//
// Ordinary `config.toml` accepts both the legacy array form and the keyed
// boolean-map form while the latter rolls out. Keeping that compatibility in
// this input-only type lets requirements stay map-only and gives us a single
// seam where arrays can be deprecated and removed later.
#[derive(Deserialize, JsonSchema)]
#[serde(untagged)]
enum ShellEnvironmentPatternListInput {
List(Vec<String>),
Map(BTreeMap<String, bool>),
}
impl ShellEnvironmentPatternListInput {
fn into_enabled_patterns(self) -> Vec<String> {
match self {
Self::List(patterns) => patterns,
Self::Map(patterns) => patterns
.into_iter()
.filter_map(|(pattern, enabled)| enabled.then_some(pattern))
.collect(),
}
}
}
fn deserialize_optional_shell_environment_pattern_list<'de, D>(
deserializer: D,
) -> Result<Option<Vec<String>>, D::Error>
where
D: serde::Deserializer<'de>,
{
Option::<ShellEnvironmentPatternListInput>::deserialize(deserializer)
.map(|value| value.map(ShellEnvironmentPatternListInput::into_enabled_patterns))
}
/// Policy for building the `env` when spawning a process via shell-like tools.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)]
#[schemars(deny_unknown_fields)]
@@ -921,12 +956,22 @@ pub struct ShellEnvironmentPolicyToml {
pub ignore_default_excludes: Option<bool>,
/// List of regular expressions.
/// List or boolean map of regular expressions.
#[serde(
default,
deserialize_with = "deserialize_optional_shell_environment_pattern_list"
)]
#[schemars(with = "Option<ShellEnvironmentPatternListInput>")]
pub exclude: Option<Vec<String>>,
pub r#set: Option<HashMap<String, String>>,
/// List of regular expressions.
/// List or boolean map of regular expressions.
#[serde(
default,
deserialize_with = "deserialize_optional_shell_environment_pattern_list"
)]
#[schemars(with = "Option<ShellEnvironmentPatternListInput>")]
pub include_only: Option<Vec<String>>,
pub experimental_use_profile: Option<bool>,
+35
View File
@@ -1,6 +1,41 @@
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn shell_environment_policy_accepts_legacy_lists_and_bool_maps() {
let legacy: ShellEnvironmentPolicyToml = toml::from_str(
r#"
exclude = ["LEGACY_*", "SHARED_*"]
include_only = ["PATH", "HOME"]
"#,
)
.expect("legacy arrays should remain valid in config.toml");
assert_eq!(
legacy,
ShellEnvironmentPolicyToml {
exclude: Some(vec!["LEGACY_*".to_string(), "SHARED_*".to_string()]),
include_only: Some(vec!["PATH".to_string(), "HOME".to_string()]),
..Default::default()
}
);
let mapped: ShellEnvironmentPolicyToml = toml::from_str(
r#"
exclude = { "DISABLED_*" = false, "ENABLED_*" = true }
include_only = { "HOME" = true, "PATH" = false }
"#,
)
.expect("boolean maps should be valid in config.toml");
assert_eq!(
mapped,
ShellEnvironmentPolicyToml {
exclude: Some(vec!["ENABLED_*".to_string()]),
include_only: Some(vec!["HOME".to_string()]),
..Default::default()
}
);
}
#[test]
fn deserialize_skill_config_with_name_selector() {
let cfg: SkillConfig = toml::from_str(
+30 -10
View File
@@ -2592,6 +2592,22 @@
],
"type": "string"
},
"ShellEnvironmentPatternListInput": {
"anyOf": [
{
"items": {
"type": "string"
},
"type": "array"
},
{
"additionalProperties": {
"type": "boolean"
},
"type": "object"
}
]
},
"ShellEnvironmentPolicyInherit": {
"oneOf": [
{
@@ -2622,11 +2638,13 @@
"description": "Policy for building the `env` when spawning a process via shell-like tools.",
"properties": {
"exclude": {
"description": "List of regular expressions.",
"items": {
"type": "string"
},
"type": "array"
"allOf": [
{
"$ref": "#/definitions/ShellEnvironmentPatternListInput"
}
],
"default": null,
"description": "List or boolean map of regular expressions."
},
"experimental_use_profile": {
"type": "boolean"
@@ -2635,11 +2653,13 @@
"type": "boolean"
},
"include_only": {
"description": "List of regular expressions.",
"items": {
"type": "string"
},
"type": "array"
"allOf": [
{
"$ref": "#/definitions/ShellEnvironmentPatternListInput"
}
],
"default": null,
"description": "List or boolean map of regular expressions."
},
"inherit": {
"$ref": "#/definitions/ShellEnvironmentPolicyInherit"
+12 -2
View File
@@ -9338,7 +9338,8 @@ allow_login_shell = true
[shell_environment_policy]
ignore_default_excludes = true
exclude = ["USER_*"]
exclude = ["USER_*", "REMOVE_*"]
include_only = ["HOME", "PATH"]
[shell_environment_policy.set]
CONFIGURED = "kept"
@@ -9381,6 +9382,14 @@ api = false
ignore_default_excludes = false
experimental_use_profile = true
[shell_environment_policy.exclude]
"MANAGED_*" = true
"REMOVE_*" = false
[shell_environment_policy.include_only]
"PATH" = false
"USER" = true
[shell_environment_policy.set]
MANAGED = "required"
@@ -9406,7 +9415,8 @@ sandbox_private_desktop = false
let expected_shell_environment_policy: ShellEnvironmentPolicy =
codex_config::types::ShellEnvironmentPolicyToml {
ignore_default_excludes: Some(false),
exclude: Some(vec!["USER_*".to_string()]),
exclude: Some(vec!["USER_*".to_string(), "MANAGED_*".to_string()]),
include_only: Some(vec!["HOME".to_string(), "USER".to_string()]),
experimental_use_profile: Some(true),
r#set: Some(HashMap::from([
("CONFIGURED".to_string(), "kept".to_string()),
+30 -4
View File
@@ -1,11 +1,13 @@
use codex_config::ConfigRequirements;
use codex_config::RequirementSource;
use codex_config::ShellEnvironmentPolicyRequirementsToml;
use codex_config::Sourced;
use codex_config::config_toml::ConfigToml;
use codex_config::types::AuthCredentialsStoreMode;
use codex_config::types::FeedbackConfigToml;
use codex_config::types::ShellEnvironmentPolicyToml;
use codex_protocol::config_types::ForcedLoginMethod;
use std::collections::BTreeMap;
use super::otel;
@@ -136,13 +138,13 @@ pub(super) fn replace_required_leaf<T: Clone + PartialEq>(
fn apply_shell_environment_policy_requirement(
configured: &mut ShellEnvironmentPolicyToml,
requirement: Option<&Sourced<ShellEnvironmentPolicyToml>>,
requirement: Option<&Sourced<ShellEnvironmentPolicyRequirementsToml>>,
startup_warnings: &mut Vec<String>,
) {
let Some(Sourced { value, source }) = requirement else {
return;
};
let ShellEnvironmentPolicyToml {
let ShellEnvironmentPolicyRequirementsToml {
inherit,
ignore_default_excludes,
exclude,
@@ -157,8 +159,8 @@ fn apply_shell_environment_policy_requirement(
&mut configured.ignore_default_excludes,
ignore_default_excludes,
);
conflict |= replace_required_leaf(&mut configured.exclude, exclude);
conflict |= replace_required_leaf(&mut configured.include_only, include_only);
conflict |= apply_required_pattern_map(&mut configured.exclude, exclude);
conflict |= apply_required_pattern_map(&mut configured.include_only, include_only);
conflict |= replace_required_leaf(
&mut configured.experimental_use_profile,
experimental_use_profile,
@@ -182,6 +184,30 @@ fn apply_shell_environment_policy_requirement(
);
}
fn apply_required_pattern_map(
configured: &mut Option<Vec<String>>,
required: &Option<BTreeMap<String, bool>>,
) -> bool {
let Some(required) = required else {
return false;
};
let configured = configured.get_or_insert_default();
// Adding an enabled pattern is additive; removing a configured pattern is
// the only case that overrides the user's effective list.
let conflict = required
.iter()
.any(|(pattern, enabled)| !enabled && configured.contains(pattern));
configured.retain(|pattern| required.get(pattern).copied().unwrap_or(true));
for (pattern, enabled) in required {
if *enabled && !configured.contains(pattern) {
configured.push(pattern.clone());
}
}
conflict
}
fn apply_feedback_requirement(
configured: &mut Option<FeedbackConfigToml>,
requirement: Option<&Sourced<FeedbackConfigToml>>,
+2 -1
View File
@@ -201,8 +201,9 @@ impl JsonSchema for ApprovalsReviewer {
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema, TS)]
#[serde(rename_all = "kebab-case")]
#[ts(export_to = "v2/")]
pub enum ShellEnvironmentPolicyInherit {
/// "Core" environment variables for the platform. On UNIX, this would
/// include HOME, LOGNAME, PATH, SHELL, and USER, among others.