Merge remote-tracking branch 'origin/main' into jif/goal-extension-app-server-wiring

This commit is contained in:
jif-oai
2026-06-01 10:34:16 +01:00
321 changed files with 10422 additions and 2504 deletions
+2
View File
@@ -12,6 +12,7 @@ jobs:
# Prevent runs on forks (requires OpenAI API key, wastes Actions minutes)
if: github.repository == 'openai/codex' && (github.event.action == 'opened' || (github.event.action == 'labeled' && github.event.label.name == 'codex-deduplicate'))
runs-on: ubuntu-latest
environment: issue-triage
permissions:
contents: read
outputs:
@@ -157,6 +158,7 @@ jobs:
needs: normalize-duplicates-all
if: ${{ needs.normalize-duplicates-all.result == 'success' && needs.normalize-duplicates-all.outputs.has_matches != 'true' }}
runs-on: ubuntu-latest
environment: issue-triage
permissions:
contents: read
outputs:
+1
View File
@@ -12,6 +12,7 @@ jobs:
# Prevent runs on forks (requires OpenAI API key, wastes Actions minutes)
if: github.repository == 'openai/codex' && (github.event.action == 'opened' || (github.event.action == 'labeled' && github.event.label.name == 'codex-label'))
runs-on: ubuntu-latest
environment: issue-triage
permissions:
contents: read
outputs:
+1
View File
@@ -1,5 +1,6 @@
{
"recommendations": [
"BazelBuild.vscode-bazel",
"rust-lang.rust-analyzer",
"charliermarsh.ruff",
"tamasfe.even-better-toml",
+2 -6
View File
@@ -2431,8 +2431,6 @@ dependencies = [
name = "codex-code-mode"
version = "0.0.0"
dependencies = [
"async-channel",
"async-trait",
"codex-protocol",
"deno_core_icudata",
"pretty_assertions",
@@ -2988,6 +2986,7 @@ dependencies = [
"codex-protocol",
"codex-state",
"codex-tools",
"codex-utils-template",
"pretty_assertions",
"serde",
"serde_json",
@@ -3034,7 +3033,6 @@ name = "codex-image-generation-extension"
version = "0.0.0"
dependencies = [
"async-trait",
"base64 0.22.1",
"codex-api",
"codex-core",
"codex-extension-api",
@@ -3049,9 +3047,6 @@ dependencies = [
"schemars 0.8.22",
"serde",
"serde_json",
"tempfile",
"tokio",
"tracing",
]
[[package]]
@@ -4175,6 +4170,7 @@ dependencies = [
"pretty_assertions",
"schemars 0.8.22",
"serde_json",
"url",
]
[[package]]
@@ -160,11 +160,13 @@ fn sample_thread_with_metadata(
ephemeral: bool,
source: AppServerSessionSource,
thread_source: Option<AppServerThreadSource>,
parent_thread_id: Option<String>,
) -> Thread {
Thread {
id: thread_id.to_string(),
session_id: format!("session-{thread_id}"),
forked_from_id: None,
parent_thread_id,
preview: "first prompt".to_string(),
ephemeral,
model_provider: "openai".to_string(),
@@ -195,6 +197,7 @@ fn sample_thread_start_response(
ephemeral,
AppServerSessionSource::Exec,
Some(AppServerThreadSource::User),
/*parent_thread_id*/ None,
),
model: model.to_string(),
model_provider: "openai".to_string(),
@@ -240,6 +243,7 @@ fn sample_thread_resume_response(
model,
AppServerSessionSource::Exec,
Some(AppServerThreadSource::User),
/*parent_thread_id*/ None,
)
}
@@ -249,9 +253,16 @@ fn sample_thread_resume_response_with_source(
model: &str,
source: AppServerSessionSource,
thread_source: Option<AppServerThreadSource>,
parent_thread_id: Option<String>,
) -> ClientResponsePayload {
ClientResponsePayload::ThreadResume(ThreadResumeResponse {
thread: sample_thread_with_metadata(thread_id, ephemeral, source, thread_source),
thread: sample_thread_with_metadata(
thread_id,
ephemeral,
source,
thread_source,
parent_thread_id,
),
model: model.to_string(),
model_provider: "openai".to_string(),
service_tier: None,
@@ -1755,6 +1766,7 @@ async fn compaction_event_ingests_custom_fact() {
agent_role: None,
}),
Some(AppServerThreadSource::Subagent),
Some(parent_thread_id.to_string()),
)),
},
&mut events,
@@ -2456,7 +2468,7 @@ fn subagent_thread_started_thread_spawn_serializes_parent_thread_id() {
SubAgentThreadStartedInput {
session_id: "session-root".to_string(),
thread_id: "thread-spawn".to_string(),
parent_thread_id: None,
parent_thread_id: Some(parent_thread_id.to_string()),
product_client_id: "codex-tui".to_string(),
client_name: "codex-tui".to_string(),
client_version: "1.0.0".to_string(),
@@ -2534,11 +2546,14 @@ fn subagent_thread_started_other_serializes_expected_shape() {
#[test]
fn subagent_thread_started_other_serializes_explicit_parent_thread_id() {
let parent_thread_id =
codex_protocol::ThreadId::from_string("33333333-3333-4333-8333-333333333333")
.expect("valid thread id");
let event = TrackEventRequest::ThreadInitialized(subagent_thread_started_event_request(
SubAgentThreadStartedInput {
session_id: "session-root".to_string(),
thread_id: "thread-guardian".to_string(),
parent_thread_id: Some("parent-thread-guardian".to_string()),
parent_thread_id: Some(parent_thread_id.to_string()),
product_client_id: "codex-tui".to_string(),
client_name: "codex-tui".to_string(),
client_version: "1.0.0".to_string(),
@@ -2553,7 +2568,7 @@ fn subagent_thread_started_other_serializes_explicit_parent_thread_id() {
assert_eq!(payload["event_params"]["subagent_source"], "guardian");
assert_eq!(
payload["event_params"]["parent_thread_id"],
"parent-thread-guardian"
"33333333-3333-4333-8333-333333333333"
);
}
@@ -2642,7 +2657,7 @@ async fn subagent_thread_started_inherits_parent_connection_for_new_thread() {
SubAgentThreadStartedInput {
session_id: "session-root".to_string(),
thread_id: "thread-review".to_string(),
parent_thread_id: None,
parent_thread_id: Some(parent_thread_id.to_string()),
product_client_id: "parent-client".to_string(),
client_name: "parent-client".to_string(),
client_version: "1.0.0".to_string(),
+1
View File
@@ -124,6 +124,7 @@ fn sample_thread(thread_id: &str) -> Thread {
id: thread_id.to_string(),
session_id: format!("session-{thread_id}"),
forked_from_id: None,
parent_thread_id: None,
preview: "first prompt".to_string(),
ephemeral: false,
model_provider: "openai".to_string(),
+3 -19
View File
@@ -1012,6 +1012,7 @@ fn analytics_hook_source(source: HookSource) -> &'static str {
HookSource::SessionFlags => "session_flags",
HookSource::Plugin => "plugin",
HookSource::CloudRequirements => "cloud_requirements",
HookSource::CloudManagedConfig => "cloud_managed_config",
HookSource::LegacyManagedConfigFile => "legacy_managed_config_file",
HookSource::LegacyManagedConfigMdm => "legacy_managed_config_mdm",
HookSource::Unknown => "unknown",
@@ -1047,9 +1048,7 @@ pub(crate) fn subagent_thread_started_event_request(
thread_source: Some(ThreadSource::Subagent),
initialization_mode: ThreadInitializationMode::New,
subagent_source: Some(subagent_source_name(&input.subagent_source)),
parent_thread_id: input
.parent_thread_id
.or_else(|| subagent_parent_thread_id(&input.subagent_source)),
parent_thread_id: input.parent_thread_id,
created_at: input.created_at,
};
ThreadInitializedEvent {
@@ -1059,22 +1058,7 @@ pub(crate) fn subagent_thread_started_event_request(
}
pub(crate) fn subagent_source_name(subagent_source: &SubAgentSource) -> String {
match subagent_source {
SubAgentSource::Review => "review".to_string(),
SubAgentSource::Compact => "compact".to_string(),
SubAgentSource::ThreadSpawn { .. } => "thread_spawn".to_string(),
SubAgentSource::MemoryConsolidation => "memory_consolidation".to_string(),
SubAgentSource::Other(other) => other.clone(),
}
}
pub(crate) fn subagent_parent_thread_id(subagent_source: &SubAgentSource) -> Option<String> {
match subagent_source {
SubAgentSource::ThreadSpawn {
parent_thread_id, ..
} => Some(parent_thread_id.to_string()),
_ => None,
}
subagent_source.kind().to_string()
}
fn analytics_hook_status(status: HookRunStatus) -> HookRunStatus {
+7 -11
View File
@@ -55,7 +55,6 @@ use crate::events::codex_hook_run_metadata;
use crate::events::codex_plugin_metadata;
use crate::events::codex_plugin_used_metadata;
use crate::events::plugin_state_event_type;
use crate::events::subagent_parent_thread_id;
use crate::events::subagent_source_name;
use crate::events::subagent_thread_started_event_request;
use crate::facts::AnalyticsFact;
@@ -267,20 +266,18 @@ impl ThreadMetadataState {
session_id: String,
session_source: &SessionSource,
thread_source: Option<ThreadSource>,
parent_thread_id: Option<String>,
initialization_mode: ThreadInitializationMode,
) -> Self {
let (subagent_source, parent_thread_id) = match session_source {
SessionSource::SubAgent(subagent_source) => (
Some(subagent_source_name(subagent_source)),
subagent_parent_thread_id(subagent_source),
),
let subagent_source = match session_source {
SessionSource::SubAgent(subagent_source) => Some(subagent_source_name(subagent_source)),
SessionSource::Cli
| SessionSource::VSCode
| SessionSource::Exec
| SessionSource::Mcp
| SessionSource::Custom(_)
| SessionSource::Internal(_)
| SessionSource::Unknown => (None, None),
| SessionSource::Unknown => None,
};
Self {
session_id,
@@ -516,10 +513,7 @@ impl AnalyticsReducer {
input: SubAgentThreadStartedInput,
out: &mut Vec<TrackEventRequest>,
) {
let parent_thread_id = input
.parent_thread_id
.clone()
.or_else(|| subagent_parent_thread_id(&input.subagent_source));
let parent_thread_id = input.parent_thread_id.clone();
let parent_connection_id = parent_thread_id
.as_ref()
.and_then(|parent_thread_id| self.threads.get(parent_thread_id))
@@ -1238,6 +1232,7 @@ impl AnalyticsReducer {
let session_source: SessionSource = thread.source.into();
let session_id = thread.session_id;
let thread_id = thread.id;
let parent_thread_id = thread.parent_thread_id;
let Some(connection_state) = self.connections.get(&connection_id) else {
return;
};
@@ -1245,6 +1240,7 @@ impl AnalyticsReducer {
session_id.clone(),
&session_source,
thread.thread_source.map(Into::into),
parent_thread_id,
initialization_mode,
);
self.threads.insert(
@@ -2002,6 +2002,7 @@
"sessionFlags",
"plugin",
"cloudRequirements",
"cloudManagedConfig",
"legacyManagedConfigFile",
"legacyManagedConfigMdm",
"unknown"
@@ -3365,6 +3366,13 @@
"null"
]
},
"parentThreadId": {
"description": "The ID of the parent thread. This will only be set if this thread is a subagent.",
"type": [
"string",
"null"
]
},
"path": {
"description": "[UNSTABLE] Path to the thread on disk.",
"type": [
@@ -7603,6 +7603,33 @@
"title": "SystemConfigLayerSource",
"type": "object"
},
{
"description": "Enterprise-managed config layer delivered by the cloud config bundle.",
"properties": {
"id": {
"description": "Stable identifier for the delivered layer.",
"type": "string"
},
"name": {
"description": "Admin-facing name for the delivered layer. This is surfaced in diagnostics so users know which cloud layer needs administrator attention.",
"type": "string"
},
"type": {
"enum": [
"enterpriseManaged"
],
"title": "EnterpriseManagedConfigLayerSourceType",
"type": "string"
}
},
"required": [
"id",
"name",
"type"
],
"title": "EnterpriseManagedConfigLayerSource",
"type": "object"
},
{
"description": "User config layer from $CODEX_HOME/config.toml. This layer is special in that it is expected to be: - writable by the user - generally outside the workspace directory",
"properties": {
@@ -7809,6 +7836,15 @@
"null"
]
},
"allowedWindowsSandboxImplementations": {
"items": {
"$ref": "#/definitions/v2/WindowsSandboxSetupMode"
},
"type": [
"array",
"null"
]
},
"computerUse": {
"anyOf": [
{
@@ -10082,6 +10118,7 @@
"sessionFlags",
"plugin",
"cloudRequirements",
"cloudManagedConfig",
"legacyManagedConfigFile",
"legacyManagedConfigMdm",
"unknown"
@@ -15476,6 +15513,13 @@
"null"
]
},
"parentThreadId": {
"description": "The ID of the parent thread. This will only be set if this thread is a subagent.",
"type": [
"string",
"null"
]
},
"path": {
"description": "[UNSTABLE] Path to the thread on disk.",
"type": [
@@ -3972,6 +3972,33 @@
"title": "SystemConfigLayerSource",
"type": "object"
},
{
"description": "Enterprise-managed config layer delivered by the cloud config bundle.",
"properties": {
"id": {
"description": "Stable identifier for the delivered layer.",
"type": "string"
},
"name": {
"description": "Admin-facing name for the delivered layer. This is surfaced in diagnostics so users know which cloud layer needs administrator attention.",
"type": "string"
},
"type": {
"enum": [
"enterpriseManaged"
],
"title": "EnterpriseManagedConfigLayerSourceType",
"type": "string"
}
},
"required": [
"id",
"name",
"type"
],
"title": "EnterpriseManagedConfigLayerSource",
"type": "object"
},
{
"description": "User config layer from $CODEX_HOME/config.toml. This layer is special in that it is expected to be: - writable by the user - generally outside the workspace directory",
"properties": {
@@ -4178,6 +4205,15 @@
"null"
]
},
"allowedWindowsSandboxImplementations": {
"items": {
"$ref": "#/definitions/WindowsSandboxSetupMode"
},
"type": [
"array",
"null"
]
},
"computerUse": {
"anyOf": [
{
@@ -6562,6 +6598,7 @@
"sessionFlags",
"plugin",
"cloudRequirements",
"cloudManagedConfig",
"legacyManagedConfigFile",
"legacyManagedConfigMdm",
"unknown"
@@ -13300,6 +13337,13 @@
"null"
]
},
"parentThreadId": {
"description": "The ID of the parent thread. This will only be set if this thread is a subagent.",
"type": [
"string",
"null"
]
},
"path": {
"description": "[UNSTABLE] Path to the thread on disk.",
"type": [
@@ -498,6 +498,33 @@
"title": "SystemConfigLayerSource",
"type": "object"
},
{
"description": "Enterprise-managed config layer delivered by the cloud config bundle.",
"properties": {
"id": {
"description": "Stable identifier for the delivered layer.",
"type": "string"
},
"name": {
"description": "Admin-facing name for the delivered layer. This is surfaced in diagnostics so users know which cloud layer needs administrator attention.",
"type": "string"
},
"type": {
"enum": [
"enterpriseManaged"
],
"title": "EnterpriseManagedConfigLayerSourceType",
"type": "string"
}
},
"required": [
"id",
"name",
"type"
],
"title": "EnterpriseManagedConfigLayerSource",
"type": "object"
},
{
"description": "User config layer from $CODEX_HOME/config.toml. This layer is special in that it is expected to be: - writable by the user - generally outside the workspace directory",
"properties": {
@@ -121,6 +121,15 @@
"null"
]
},
"allowedWindowsSandboxImplementations": {
"items": {
"$ref": "#/definitions/WindowsSandboxSetupMode"
},
"type": [
"array",
"null"
]
},
"computerUse": {
"anyOf": [
{
@@ -485,6 +494,13 @@
"live"
],
"type": "string"
},
"WindowsSandboxSetupMode": {
"enum": [
"elevated",
"unelevated"
],
"type": "string"
}
},
"properties": {
@@ -73,6 +73,33 @@
"title": "SystemConfigLayerSource",
"type": "object"
},
{
"description": "Enterprise-managed config layer delivered by the cloud config bundle.",
"properties": {
"id": {
"description": "Stable identifier for the delivered layer.",
"type": "string"
},
"name": {
"description": "Admin-facing name for the delivered layer. This is surfaced in diagnostics so users know which cloud layer needs administrator attention.",
"type": "string"
},
"type": {
"enum": [
"enterpriseManaged"
],
"title": "EnterpriseManagedConfigLayerSourceType",
"type": "string"
}
},
"required": [
"id",
"name",
"type"
],
"title": "EnterpriseManagedConfigLayerSource",
"type": "object"
},
{
"description": "User config layer from $CODEX_HOME/config.toml. This layer is special in that it is expected to be: - writable by the user - generally outside the workspace directory",
"properties": {
@@ -166,6 +166,7 @@
"sessionFlags",
"plugin",
"cloudRequirements",
"cloudManagedConfig",
"legacyManagedConfigFile",
"legacyManagedConfigMdm",
"unknown"
@@ -166,6 +166,7 @@
"sessionFlags",
"plugin",
"cloudRequirements",
"cloudManagedConfig",
"legacyManagedConfigFile",
"legacyManagedConfigMdm",
"unknown"
@@ -130,6 +130,7 @@
"sessionFlags",
"plugin",
"cloudRequirements",
"cloudManagedConfig",
"legacyManagedConfigFile",
"legacyManagedConfigMdm",
"unknown"
@@ -1036,6 +1036,13 @@
"null"
]
},
"parentThreadId": {
"description": "The ID of the parent thread. This will only be set if this thread is a subagent.",
"type": [
"string",
"null"
]
},
"path": {
"description": "[UNSTABLE] Path to the thread on disk.",
"type": [
@@ -851,6 +851,13 @@
"null"
]
},
"parentThreadId": {
"description": "The ID of the parent thread. This will only be set if this thread is a subagent.",
"type": [
"string",
"null"
]
},
"path": {
"description": "[UNSTABLE] Path to the thread on disk.",
"type": [
@@ -851,6 +851,13 @@
"null"
]
},
"parentThreadId": {
"description": "The ID of the parent thread. This will only be set if this thread is a subagent.",
"type": [
"string",
"null"
]
},
"path": {
"description": "[UNSTABLE] Path to the thread on disk.",
"type": [
@@ -851,6 +851,13 @@
"null"
]
},
"parentThreadId": {
"description": "The ID of the parent thread. This will only be set if this thread is a subagent.",
"type": [
"string",
"null"
]
},
"path": {
"description": "[UNSTABLE] Path to the thread on disk.",
"type": [
@@ -1036,6 +1036,13 @@
"null"
]
},
"parentThreadId": {
"description": "The ID of the parent thread. This will only be set if this thread is a subagent.",
"type": [
"string",
"null"
]
},
"path": {
"description": "[UNSTABLE] Path to the thread on disk.",
"type": [
@@ -851,6 +851,13 @@
"null"
]
},
"parentThreadId": {
"description": "The ID of the parent thread. This will only be set if this thread is a subagent.",
"type": [
"string",
"null"
]
},
"path": {
"description": "[UNSTABLE] Path to the thread on disk.",
"type": [
@@ -1036,6 +1036,13 @@
"null"
]
},
"parentThreadId": {
"description": "The ID of the parent thread. This will only be set if this thread is a subagent.",
"type": [
"string",
"null"
]
},
"path": {
"description": "[UNSTABLE] Path to the thread on disk.",
"type": [
@@ -851,6 +851,13 @@
"null"
]
},
"parentThreadId": {
"description": "The ID of the parent thread. This will only be set if this thread is a subagent.",
"type": [
"string",
"null"
]
},
"path": {
"description": "[UNSTABLE] Path to the thread on disk.",
"type": [
@@ -851,6 +851,13 @@
"null"
]
},
"parentThreadId": {
"description": "The ID of the parent thread. This will only be set if this thread is a subagent.",
"type": [
"string",
"null"
]
},
"path": {
"description": "[UNSTABLE] Path to the thread on disk.",
"type": [
@@ -8,7 +8,17 @@ export type ConfigLayerSource = { "type": "mdm", domain: string, key: string, }
* This is the path to the system config.toml file, though it is not
* guaranteed to exist.
*/
file: AbsolutePathBuf, } | { "type": "user",
file: AbsolutePathBuf, } | { "type": "enterpriseManaged",
/**
* Stable identifier for the delivered layer.
*/
id: string,
/**
* Admin-facing name for the delivered layer. This is surfaced in
* diagnostics so users know which cloud layer needs administrator
* attention.
*/
name: string, } | { "type": "user",
/**
* This is the path to the user's config.toml file, though it is not
* guaranteed to exist.
@@ -6,5 +6,6 @@ import type { AskForApproval } from "./AskForApproval";
import type { ComputerUseRequirements } from "./ComputerUseRequirements";
import type { ResidencyRequirement } from "./ResidencyRequirement";
import type { SandboxMode } from "./SandboxMode";
import type { WindowsSandboxSetupMode } from "./WindowsSandboxSetupMode";
export type ConfigRequirements = {allowedApprovalPolicies: Array<AskForApproval> | null, allowedSandboxModes: Array<SandboxMode> | null, allowedPermissions: Array<string> | null, allowedWebSearchModes: Array<WebSearchMode> | null, allowManagedHooksOnly: boolean | null, allowAppshots: boolean | null, computerUse: ComputerUseRequirements | null, featureRequirements: { [key in string]?: boolean } | null, enforceResidency: ResidencyRequirement | null};
export type ConfigRequirements = {allowedApprovalPolicies: Array<AskForApproval> | null, allowedSandboxModes: Array<SandboxMode> | null, allowedWindowsSandboxImplementations: Array<WindowsSandboxSetupMode> | null, allowedPermissions: Array<string> | null, allowedWebSearchModes: Array<WebSearchMode> | null, allowManagedHooksOnly: boolean | null, allowAppshots: boolean | null, computerUse: ComputerUseRequirements | null, featureRequirements: { [key in string]?: boolean } | null, enforceResidency: ResidencyRequirement | null};
@@ -2,4 +2,4 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type HookSource = "system" | "user" | "project" | "mdm" | "sessionFlags" | "plugin" | "cloudRequirements" | "legacyManagedConfigFile" | "legacyManagedConfigMdm" | "unknown";
export type HookSource = "system" | "user" | "project" | "mdm" | "sessionFlags" | "plugin" | "cloudRequirements" | "cloudManagedConfig" | "legacyManagedConfigFile" | "legacyManagedConfigMdm" | "unknown";
@@ -17,6 +17,10 @@ sessionId: string,
* Source thread id when this thread was created by forking another thread.
*/
forkedFromId: string | null,
/**
* The ID of the parent thread. This will only be set if this thread is a subagent.
*/
parentThreadId: string | null,
/**
* Usually the first user message in the thread, if available.
*/
@@ -2328,6 +2328,7 @@ mod tests {
id: "67e55044-10b1-426f-9247-bb680e5fe0c8".to_string(),
session_id: "67e55044-10b1-426f-9247-bb680e5fe0c7".to_string(),
forked_from_id: None,
parent_thread_id: None,
preview: "first prompt".to_string(),
ephemeral: true,
model_provider: "openai".to_string(),
@@ -2370,6 +2371,7 @@ mod tests {
"id": "67e55044-10b1-426f-9247-bb680e5fe0c8",
"sessionId": "67e55044-10b1-426f-9247-bb680e5fe0c7",
"forkedFromId": null,
"parentThreadId": null,
"preview": "first prompt",
"ephemeral": true,
"modelProvider": "openai",
@@ -1,6 +1,7 @@
use super::ApprovalsReviewer;
use super::AskForApproval;
use super::SandboxMode;
use super::WindowsSandboxSetupMode;
use super::shared::default_enabled;
use codex_experimental_api_macros::ExperimentalApi;
use codex_protocol::config_types::AutoCompactTokenLimitScope;
@@ -42,6 +43,19 @@ pub enum ConfigLayerSource {
file: AbsolutePathBuf,
},
/// Enterprise-managed config layer delivered by the cloud config bundle.
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
EnterpriseManaged {
/// Stable identifier for the delivered layer.
id: String,
/// Admin-facing name for the delivered layer. This is surfaced in
/// diagnostics so users know which cloud layer needs administrator
/// attention.
name: String,
},
/// User config layer from $CODEX_HOME/config.toml. This layer is special
/// in that it is expected to be:
/// - writable by the user
@@ -89,6 +103,7 @@ impl ConfigLayerSource {
match self {
ConfigLayerSource::Mdm { .. } => 0,
ConfigLayerSource::System { .. } => 10,
ConfigLayerSource::EnterpriseManaged { .. } => 15,
ConfigLayerSource::User { profile, .. } => {
if profile.is_some() {
21
@@ -358,6 +373,7 @@ pub struct ConfigRequirements {
#[experimental("configRequirements/read.allowedApprovalsReviewers")]
pub allowed_approvals_reviewers: Option<Vec<ApprovalsReviewer>>,
pub allowed_sandbox_modes: Option<Vec<SandboxMode>>,
pub allowed_windows_sandbox_implementations: Option<Vec<WindowsSandboxSetupMode>>,
pub allowed_permissions: Option<Vec<String>>,
pub allowed_web_search_modes: Option<Vec<WebSearchMode>>,
pub allow_managed_hooks_only: Option<bool>,
@@ -48,6 +48,7 @@ v2_enum_from_core!(
SessionFlags,
Plugin,
CloudRequirements,
CloudManagedConfig,
LegacyManagedConfigFile,
LegacyManagedConfigMdm,
Unknown,
@@ -142,6 +142,7 @@ fn thread_resume_response_round_trips_initial_turns_page() {
id: "thr_123".to_string(),
session_id: "thr_123".to_string(),
forked_from_id: None,
parent_thread_id: None,
preview: String::new(),
ephemeral: false,
model_provider: "openai".to_string(),
@@ -1670,6 +1671,7 @@ fn config_requirements_granular_allowed_approval_policy_is_marked_experimental()
}]),
allowed_approvals_reviewers: None,
allowed_sandbox_modes: None,
allowed_windows_sandbox_implementations: None,
allowed_permissions: None,
allowed_web_search_modes: None,
allow_managed_hooks_only: None,
@@ -3580,6 +3582,7 @@ fn thread_lifecycle_responses_default_missing_optional_fields() {
let fork: ThreadForkResponse = serde_json::from_value(response).expect("thread/fork response");
assert_eq!(start.instruction_sources, Vec::<AbsolutePathBuf>::new());
assert_eq!(start.thread.parent_thread_id, None);
assert_eq!(resume.instruction_sources, Vec::<AbsolutePathBuf>::new());
assert_eq!(fork.instruction_sources, Vec::<AbsolutePathBuf>::new());
assert_eq!(start.active_permission_profile, None);
@@ -108,6 +108,8 @@ pub struct Thread {
pub session_id: String,
/// Source thread id when this thread was created by forking another thread.
pub forked_from_id: Option<String>,
/// The ID of the parent thread. This will only be set if this thread is a subagent.
pub parent_thread_id: Option<String>,
/// Usually the first user message in the thread, if available.
pub preview: String,
/// Whether the thread is ephemeral and should not be materialized on disk.
+2 -2
View File
@@ -134,7 +134,7 @@ Example with notification opt-out:
- `thread/resume` — reopen an existing thread by id so subsequent `turn/start` calls append to it. Accepts the same permission override rules as `thread/start`.
- `thread/fork` — fork an existing thread into a new thread id by copying the stored history; if the source thread is currently mid-turn, the fork records the same interruption marker as `turn/interrupt` instead of inheriting an unmarked partial turn suffix. The returned `thread.forkedFromId` points at the source thread when known. Accepts `ephemeral: true` for an in-memory temporary fork, emits `thread/started` (including the current `thread.status`), and auto-subscribes you to turn/item events for the new thread. Experimental clients can pass `excludeTurns: true` when they plan to page fork history via `thread/turns/list` instead of receiving the full turn array immediately. Accepts the same permission override rules as `thread/start`.
- `thread/start`, `thread/resume`, and `thread/fork` responses include the legacy `sandbox` compatibility projection. Experimental clients can read `runtimeWorkspaceRoots` for the thread-scoped runtime roots and `activePermissionProfile` for the named or implicit built-in profile identity/provenance when known.
- `thread/list` — page through stored rollouts; supports cursor-based pagination and optional `modelProviders`, `sourceKinds`, `archived`, `cwd`, and `searchTerm` filters. Each returned `thread` includes `status` (`ThreadStatus`), defaulting to `notLoaded` when the thread is not currently loaded.
- `thread/list` — page through stored rollouts; supports cursor-based pagination and optional `modelProviders`, `sourceKinds`, `archived`, `cwd`, and `searchTerm` filters. Each returned `thread` includes `status` (`ThreadStatus`), defaulting to `notLoaded` when the thread is not currently loaded. Subagent threads also include `parentThreadId` when the immediate control/spawn parent is known.
- `thread/loaded/list` — list the thread ids currently loaded in memory.
- `thread/read` — read a stored thread by id without resuming it; optionally include turns via `includeTurns`. The returned `thread` includes `status` (`ThreadStatus`), defaulting to `notLoaded` when the thread is not currently loaded.
- `thread/turns/list` — experimental; page through a stored thread’s turn history without resuming it; supports cursor-based pagination with `sortDirection`, `itemsView`, `nextCursor`, and `backwardsCursor`.
@@ -424,7 +424,7 @@ Later, after the idle unload timeout:
### Example: Read a thread
Use `thread/read` to fetch a stored thread by id without resuming it. Pass `includeTurns` when you want thread history loaded into `thread.turns`. The returned thread includes `agentNickname` and `agentRole` for AgentControl-spawned thread sub-agents when available.
Use `thread/read` to fetch a stored thread by id without resuming it. Pass `includeTurns` when you want thread history loaded into `thread.turns`. The returned thread includes `parentThreadId`, `agentNickname`, and `agentRole` for subagent threads when available.
```json
{ "method": "thread/read", "id": 22, "params": { "threadId": "thr_123" } }
@@ -2095,6 +2095,7 @@ mod tests {
use codex_protocol::items::build_hook_prompt_message;
use codex_protocol::models::FileSystemPermissions as CoreFileSystemPermissions;
use codex_protocol::models::NetworkPermissions as CoreNetworkPermissions;
use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::FileSystemAccessMode;
use codex_protocol::permissions::FileSystemPath;
use codex_protocol::permissions::FileSystemSandboxEntry;
@@ -2110,7 +2111,6 @@ mod tests {
use codex_protocol::protocol::RateLimitSnapshot;
use codex_protocol::protocol::RateLimitWindow;
use codex_protocol::protocol::RolloutItem;
use codex_protocol::protocol::SandboxPolicy;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::TokenUsage;
use codex_protocol::protocol::TokenUsageInfo;
@@ -2170,6 +2170,7 @@ mod tests {
thread_id,
rollout_path: None,
forked_from_id: None,
parent_thread_id: None,
preview: "fallback preview".to_string(),
name: Some("Rollback thread".to_string()),
model_provider: "openai".to_string(),
@@ -2187,7 +2188,7 @@ mod tests {
agent_path: None,
git_info: None,
approval_mode: AskForApproval::OnRequest,
sandbox_policy: SandboxPolicy::new_read_only_policy(),
permission_profile: PermissionProfile::read_only(),
token_usage: None,
first_user_message: Some("before rollback".to_string()),
history: Some(StoredThreadHistory {
@@ -624,6 +624,9 @@ fn override_message(layer: &ConfigLayerSource) -> String {
ConfigLayerSource::System { file } => {
format!("Overridden by managed config (system): {}", file.display())
}
ConfigLayerSource::EnterpriseManaged { id: _, name } => {
format!("Overridden by enterprise-managed config: {name}")
}
ConfigLayerSource::Project { dot_codex_folder } => format!(
"Overridden by project config: {}/{CONFIG_TOML_FILE}",
dot_codex_folder.display(),
@@ -30,6 +30,7 @@ use codex_app_server_protocol::NetworkRequirements;
use codex_app_server_protocol::NetworkUnixSocketPermission;
use codex_app_server_protocol::SandboxMode;
use codex_app_server_protocol::ServerNotification;
use codex_app_server_protocol::WindowsSandboxSetupMode;
use codex_chatgpt::connectors;
use codex_config::ConfigRequirementsToml;
use codex_config::HookEventsToml;
@@ -420,6 +421,23 @@ fn map_requirements_toml_to_api(requirements: ConfigRequirementsToml) -> ConfigR
.filter_map(map_sandbox_mode_requirement_to_api)
.collect()
}),
allowed_windows_sandbox_implementations: requirements.windows.and_then(|windows| {
windows
.allowed_sandbox_implementations
.map(|implementations| {
implementations
.into_iter()
.map(|implementation| match implementation {
codex_config::types::WindowsSandboxModeToml::Elevated => {
WindowsSandboxSetupMode::Elevated
}
codex_config::types::WindowsSandboxModeToml::Unelevated => {
WindowsSandboxSetupMode::Unelevated
}
})
.collect()
})
}),
allowed_permissions: requirements.allowed_permissions,
allowed_web_search_modes: requirements.allowed_web_search_modes.map(|modes| {
let mut normalized = modes
@@ -634,8 +652,10 @@ 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::WindowsSandboxSetupMode;
use codex_config::ComputerUseRequirementsToml;
use codex_config::ConfigRequirementsToml;
use codex_config::WindowsRequirementsToml;
use pretty_assertions::assert_eq;
#[test]
@@ -687,4 +707,25 @@ mod tests {
Some(false)
);
}
#[test]
fn requirements_api_includes_allowed_windows_sandbox_implementations() {
let mapped = map_requirements_toml_to_api(ConfigRequirementsToml {
windows: Some(WindowsRequirementsToml {
allowed_sandbox_implementations: Some(vec![
codex_config::types::WindowsSandboxModeToml::Elevated,
codex_config::types::WindowsSandboxModeToml::Unelevated,
]),
}),
..ConfigRequirementsToml::default()
});
assert_eq!(
mapped.allowed_windows_sandbox_implementations,
Some(vec![
WindowsSandboxSetupMode::Elevated,
WindowsSandboxSetupMode::Unelevated,
])
);
}
}
@@ -1509,7 +1509,7 @@ impl PluginRequestProcessor {
let environment_manager = self.thread_manager.environment_manager();
let (all_connectors_result, accessible_connectors_result) = tokio::join!(
connectors::list_all_connectors_with_options(config, /*force_refetch*/ true),
connectors::list_all_connectors_with_options(config, /*force_refetch*/ false),
connectors::list_accessible_connectors_from_mcp_tools_with_environment_manager(
config,
/*force_refetch*/ true,
@@ -1308,7 +1308,7 @@ impl ThreadRequestProcessor {
params: ThreadArchiveParams,
) -> Result<(ThreadArchiveResponse, Vec<String>), JSONRPCErrorError> {
let thread_id = ThreadId::from_string(&params.thread_id)
.map_err(|err| invalid_request(format!("invalid thread id: {err}")))?;
.map_err(|err| invalid_request(format!("invalid session id: {err}")))?;
let mut thread_ids = vec![thread_id];
if let Some(state_db_ctx) = self.state_db.as_ref() {
@@ -1317,7 +1317,7 @@ impl ThreadRequestProcessor {
.await
.map_err(|err| {
internal_error(format!(
"failed to list spawned descendants for thread id {thread_id}: {err}"
"failed to list spawned descendants for session {thread_id}: {err}"
))
})?;
let mut seen = HashSet::from([thread_id]);
@@ -1629,7 +1629,7 @@ impl ThreadRequestProcessor {
params: ThreadUnarchiveParams,
) -> Result<(ThreadUnarchiveResponse, String), JSONRPCErrorError> {
let thread_id = ThreadId::from_string(&params.thread_id)
.map_err(|err| invalid_request(format!("invalid thread id: {err}")))?;
.map_err(|err| invalid_request(format!("invalid session id: {err}")))?;
let fallback_provider = self.config.model_provider_id.clone();
let stored_thread = self
@@ -2968,7 +2968,7 @@ impl ThreadRequestProcessor {
let existing_thread_id = match ThreadId::from_string(thread_id) {
Ok(id) => id,
Err(err) => {
return Err(invalid_request(format!("invalid thread id: {err}")));
return Err(invalid_request(format!("invalid session id: {err}")));
}
};
let params = StoreReadThreadParams {
@@ -2979,7 +2979,15 @@ impl ThreadRequestProcessor {
self.thread_store.read_thread(params).await
};
result.map_err(thread_store_resume_read_error)
let stored_thread = result.map_err(thread_store_resume_read_error)?;
if stored_thread.archived_at.is_some() {
let thread_id = stored_thread.thread_id;
return Err(invalid_request(format!(
"session {thread_id} is archived. Run `codex unarchive {thread_id}` to unarchive it first."
)));
}
Ok(stored_thread)
}
async fn stored_thread_to_initial_history(
@@ -3964,7 +3972,7 @@ fn thread_store_archive_error(operation: &str, err: ThreadStoreError) -> JSONRPC
ThreadStoreError::Unsupported {
operation: unsupported_operation,
} => unsupported_thread_store_operation(unsupported_operation),
err => internal_error(format!("failed to {operation} thread: {err}")),
err => internal_error(format!("failed to {operation} session: {err}")),
}
}
@@ -4004,6 +4012,7 @@ pub(crate) fn thread_from_stored_thread(
id: thread_id.clone(),
session_id: thread_id,
forked_from_id: thread.forked_from_id.map(|id| id.to_string()),
parent_thread_id: thread.parent_thread_id.map(|id| id.to_string()),
preview: thread.preview,
ephemeral: false,
model_provider: if thread.model_provider.is_empty() {
@@ -4212,6 +4221,7 @@ fn build_thread_from_snapshot(
id: thread_id.to_string(),
session_id,
forked_from_id: None,
parent_thread_id: config_snapshot.parent_thread_id.map(|id| id.to_string()),
preview: String::new(),
ephemeral: config_snapshot.ephemeral,
model_provider: config_snapshot.model_provider_id.clone(),
@@ -68,13 +68,13 @@ mod thread_processor_behavior_tests {
use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_DANGER_FULL_ACCESS;
use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_READ_ONLY;
use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_WORKSPACE;
use codex_protocol::models::PermissionProfile;
use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::permissions::FileSystemAccessMode;
use codex_protocol::permissions::FileSystemPath;
use codex_protocol::permissions::FileSystemSandboxEntry;
use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::SandboxPolicy;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
use codex_state::ThreadMetadataBuilder;
@@ -395,6 +395,7 @@ mod thread_processor_behavior_tests {
thread_id,
rollout_path: Some(PathBuf::from("/tmp/thread.jsonl")),
forked_from_id: None,
parent_thread_id: None,
preview: "preview".to_string(),
name: None,
model_provider: "openai".to_string(),
@@ -412,7 +413,7 @@ mod thread_processor_behavior_tests {
agent_path: None,
git_info: None,
approval_mode: AskForApproval::OnRequest,
sandbox_policy: SandboxPolicy::new_read_only_policy(),
permission_profile: PermissionProfile::read_only(),
token_usage: None,
first_user_message: Some("first user message".to_string()),
history: None,
@@ -681,6 +682,7 @@ mod thread_processor_behavior_tests {
},
},
session_source: SessionSource::Cli,
parent_thread_id: None,
thread_source: None,
};
@@ -172,6 +172,7 @@ mod tests {
id: "thread-1".to_string(),
session_id: "session-1".to_string(),
forked_from_id: None,
parent_thread_id: None,
preview: "preview".to_string(),
ephemeral: false,
model_provider: "mock_provider".to_string(),
@@ -305,6 +305,7 @@ pub(crate) fn summary_to_thread(
id: thread_id.clone(),
session_id: thread_id,
forked_from_id: None,
parent_thread_id: None,
preview,
ephemeral: false,
model_provider,
@@ -41,6 +41,29 @@ impl WindowsSandboxRequestProcessor {
request_id: &ConnectionRequestId,
params: WindowsSandboxSetupStartParams,
) -> Result<(), JSONRPCErrorError> {
// Validate requirements before acknowledging setup so callers do not get a
// `started` response for a Windows sandbox mode that cannot be persisted.
let command_cwd = params
.cwd
.map(PathBuf::from)
.unwrap_or_else(|| self.config.cwd.to_path_buf());
let config = self
.config_manager
.load_for_cwd(
/*request_overrides*/ None,
ConfigOverrides {
cwd: Some(command_cwd.clone()),
..Default::default()
},
Some(command_cwd.clone()),
)
.await
.map_err(|err| config_load_error(&err))?;
let setup_mode = resolve_allowed_windows_sandbox_setup_mode(
config.config_layer_stack.requirements(),
params.mode,
)?;
self.outgoing
.send_response(
request_id.clone(),
@@ -48,46 +71,22 @@ impl WindowsSandboxRequestProcessor {
)
.await;
let mode = match params.mode {
WindowsSandboxSetupMode::Elevated => CoreWindowsSandboxSetupMode::Elevated,
WindowsSandboxSetupMode::Unelevated => CoreWindowsSandboxSetupMode::Unelevated,
};
let config = Arc::clone(&self.config);
let config_manager = self.config_manager.clone();
let command_cwd = params
.cwd
.map(PathBuf::from)
.unwrap_or_else(|| config.cwd.to_path_buf());
let outgoing = Arc::clone(&self.outgoing);
let connection_id = request_id.connection_id;
tokio::spawn(async move {
let derived_config = config_manager
.load_for_cwd(
/*request_overrides*/ None,
ConfigOverrides {
cwd: Some(command_cwd.clone()),
..Default::default()
},
Some(command_cwd.clone()),
)
.await;
let setup_result = match derived_config {
Ok(config) => {
let setup_request = WindowsSandboxSetupRequest {
mode,
permission_profile: config.permissions.effective_permission_profile(),
workspace_roots: config.effective_workspace_roots(),
command_cwd,
env_map: std::env::vars().collect(),
codex_home: config.codex_home.to_path_buf(),
};
codex_core::windows_sandbox::run_windows_sandbox_setup(setup_request).await
}
Err(err) => Err(err.into()),
let setup_request = WindowsSandboxSetupRequest {
mode: setup_mode,
permission_profile: config.permissions.effective_permission_profile(),
workspace_roots: config.effective_workspace_roots(),
command_cwd,
env_map: std::env::vars().collect(),
codex_home: config.codex_home.to_path_buf(),
};
let setup_result =
codex_core::windows_sandbox::run_windows_sandbox_setup(setup_request).await;
let notification = WindowsSandboxSetupCompletedNotification {
mode: match mode {
mode: match setup_mode {
CoreWindowsSandboxSetupMode::Elevated => WindowsSandboxSetupMode::Elevated,
CoreWindowsSandboxSetupMode::Unelevated => WindowsSandboxSetupMode::Unelevated,
},
@@ -105,6 +104,28 @@ impl WindowsSandboxRequestProcessor {
}
}
/// Resolves the requested API mode after checking that managed requirements allow it.
fn resolve_allowed_windows_sandbox_setup_mode(
requirements: &codex_config::ConfigRequirements,
requested_mode: WindowsSandboxSetupMode,
) -> Result<CoreWindowsSandboxSetupMode, JSONRPCErrorError> {
let (setup_mode, config_mode) = match requested_mode {
WindowsSandboxSetupMode::Elevated => (
CoreWindowsSandboxSetupMode::Elevated,
codex_config::types::WindowsSandboxModeToml::Elevated,
),
WindowsSandboxSetupMode::Unelevated => (
CoreWindowsSandboxSetupMode::Unelevated,
codex_config::types::WindowsSandboxModeToml::Unelevated,
),
};
requirements
.windows_sandbox_mode
.can_set(&Some(config_mode))
.map_err(|err| invalid_request(format!("invalid Windows sandbox setup mode: {err}")))?;
Ok(setup_mode)
}
fn determine_windows_sandbox_readiness(config: &Config) -> WindowsSandboxReadinessResponse {
if !cfg!(windows) {
return WindowsSandboxReadinessResponse {
@@ -140,6 +161,34 @@ fn determine_windows_sandbox_readiness_from_state(
#[cfg(test)]
mod tests {
use super::*;
use crate::error_code::INVALID_REQUEST_ERROR_CODE;
use codex_config::ConfigRequirements;
use codex_config::Constrained;
use codex_config::ConstrainedWithSource;
use codex_config::types::WindowsSandboxModeToml;
#[test]
fn resolve_allowed_windows_sandbox_setup_mode_rejects_disallowed_mode() {
let requirements = ConfigRequirements {
windows_sandbox_mode: ConstrainedWithSource::new(
Constrained::allow_only(Some(WindowsSandboxModeToml::Elevated)),
/*source*/ None,
),
..Default::default()
};
let err = resolve_allowed_windows_sandbox_setup_mode(
&requirements,
WindowsSandboxSetupMode::Unelevated,
)
.expect_err("unelevated setup should be rejected");
assert_eq!(err.code, INVALID_REQUEST_ERROR_CODE);
assert!(
err.message.contains("invalid Windows sandbox setup mode"),
"{err:?}"
);
}
#[test]
fn determine_windows_sandbox_readiness_reports_not_configured_when_disabled() {
+1
View File
@@ -891,6 +891,7 @@ mod tests {
id: thread_id.to_string(),
session_id: thread_id.to_string(),
forked_from_id: None,
parent_thread_id: None,
preview: String::new(),
ephemeral: false,
model_provider: "mock-provider".to_string(),
+1
View File
@@ -38,6 +38,7 @@ pub use responses::create_final_assistant_message_sse_response;
pub use responses::create_request_permissions_sse_response;
pub use responses::create_request_user_input_sse_response;
pub use responses::create_shell_command_sse_response;
pub use rollout::create_fake_parented_rollout_with_source;
pub use rollout::create_fake_rollout;
pub use rollout::create_fake_rollout_with_source;
pub use rollout::create_fake_rollout_with_text_elements;
@@ -52,6 +52,7 @@ fn preset_to_info(preset: &ModelPreset, priority: i32) -> ModelInfo {
input_modalities: default_input_modalities(),
used_fallback_model_metadata: false,
supports_search_tool: false,
tool_mode: None,
}
}
@@ -118,6 +118,53 @@ pub fn create_fake_rollout_with_source(
model_provider: Option<&str>,
git_info: Option<GitInfo>,
source: SessionSource,
) -> Result<String> {
create_fake_rollout_with_source_and_parent_thread_id(
codex_home,
filename_ts,
meta_rfc3339,
preview,
model_provider,
git_info,
source,
/*parent_thread_id*/ None,
)
}
/// Create a minimal rollout file with an explicit session source and control parent.
#[allow(clippy::too_many_arguments)]
pub fn create_fake_parented_rollout_with_source(
codex_home: &Path,
filename_ts: &str,
meta_rfc3339: &str,
preview: &str,
model_provider: Option<&str>,
git_info: Option<GitInfo>,
source: SessionSource,
parent_thread_id: ThreadId,
) -> Result<String> {
create_fake_rollout_with_source_and_parent_thread_id(
codex_home,
filename_ts,
meta_rfc3339,
preview,
model_provider,
git_info,
source,
Some(parent_thread_id),
)
}
#[allow(clippy::too_many_arguments)]
fn create_fake_rollout_with_source_and_parent_thread_id(
codex_home: &Path,
filename_ts: &str,
meta_rfc3339: &str,
preview: &str,
model_provider: Option<&str>,
git_info: Option<GitInfo>,
source: SessionSource,
parent_thread_id: Option<ThreadId>,
) -> Result<String> {
let uuid = Uuid::new_v4();
let uuid_str = uuid.to_string();
@@ -133,6 +180,7 @@ pub fn create_fake_rollout_with_source(
let meta = SessionMeta {
id: conversation_id,
forked_from_id: None,
parent_thread_id,
timestamp: meta_rfc3339.to_string(),
cwd: PathBuf::from("/"),
originator: "codex".to_string(),
@@ -217,6 +265,7 @@ pub fn create_fake_rollout_with_text_elements(
let meta = SessionMeta {
id: conversation_id,
forked_from_id: None,
parent_thread_id: None,
timestamp: meta_rfc3339.to_string(),
cwd: PathBuf::from("/"),
originator: "codex".to_string(),
@@ -124,6 +124,7 @@ async fn get_conversation_summary_by_thread_id_reads_pathless_store_thread() ->
.create_thread(CreateThreadParams {
thread_id,
forked_from_id: None,
parent_thread_id: None,
source: SessionSource::Cli,
thread_source: None,
base_instructions: BaseInstructions::default(),
@@ -1,5 +1,6 @@
use anyhow::Result;
use app_test_support::McpProcess;
use app_test_support::create_fake_parented_rollout_with_source;
use app_test_support::create_fake_rollout;
use app_test_support::to_response;
use codex_app_server_protocol::JSONRPCResponse;
@@ -8,8 +9,11 @@ use codex_app_server_protocol::ReviewDelivery;
use codex_app_server_protocol::ReviewStartParams;
use codex_app_server_protocol::ReviewStartResponse;
use codex_app_server_protocol::ReviewTarget;
use codex_app_server_protocol::SessionSource as ApiSessionSource;
use codex_app_server_protocol::ThreadForkParams;
use codex_app_server_protocol::ThreadForkResponse;
use codex_app_server_protocol::ThreadResumeParams;
use codex_app_server_protocol::ThreadResumeResponse;
use codex_app_server_protocol::ThreadSource;
use codex_app_server_protocol::ThreadStartParams;
use codex_app_server_protocol::ThreadStartResponse;
@@ -18,6 +22,9 @@ use codex_app_server_protocol::TurnStartResponse;
use codex_app_server_protocol::TurnSteerParams;
use codex_app_server_protocol::TurnSteerResponse;
use codex_app_server_protocol::UserInput as V2UserInput;
use codex_protocol::ThreadId as CoreThreadId;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
use core_test_support::responses;
use core_test_support::skip_if_no_network;
use pretty_assertions::assert_eq;
@@ -192,7 +199,7 @@ async fn turn_start_sends_fork_lineage_in_turn_metadata_for_thread_fork_v2() ->
}
#[tokio::test]
async fn review_start_sends_fork_lineage_in_turn_metadata_for_thread_fork_v2() -> Result<()> {
async fn review_start_sends_parent_lineage_in_turn_metadata_for_thread_fork_v2() -> Result<()> {
skip_if_no_network!(Ok(()));
let review_payload = serde_json::json!({
@@ -270,8 +277,9 @@ async fn review_start_sends_fork_lineage_in_turn_metadata_for_thread_fork_v2() -
request.header("x-openai-subagent").as_deref(),
Some("review")
);
assert!(metadata.get("forked_from_thread_id").is_none());
assert_eq!(
metadata["forked_from_thread_id"].as_str(),
metadata["parent_thread_id"].as_str(),
Some(review_thread_id.as_str())
);
let review_request_thread_id = metadata["thread_id"]
@@ -290,6 +298,104 @@ async fn review_start_sends_fork_lineage_in_turn_metadata_for_thread_fork_v2() -
Ok(())
}
#[tokio::test]
async fn turn_start_sends_other_subagent_lineage_after_cold_thread_resume_v2() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = responses::start_mock_server().await;
let response_mock = responses::mount_sse_once(
&server,
responses::sse(vec![
responses::ev_response_created("resp-1"),
responses::ev_assistant_message("msg-1", "Done"),
responses::ev_completed("resp-1"),
]),
)
.await;
let codex_home = TempDir::new()?;
create_config_toml(
codex_home.path(),
&server.uri(),
/*supports_websockets*/ false,
)?;
let parent_thread_id = CoreThreadId::new();
let parent_thread_id_str = parent_thread_id.to_string();
let subagent_thread_id = create_fake_parented_rollout_with_source(
codex_home.path(),
"2025-01-05T12-00-00",
"2025-01-05T12:00:00Z",
"Saved subagent message",
Some("mock_provider"),
/*git_info*/ None,
SessionSource::SubAgent(SubAgentSource::Other("guardian".to_string())),
parent_thread_id,
)?;
let mut mcp = McpProcess::new(codex_home.path()).await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let resume_req = mcp
.send_thread_resume_request(ThreadResumeParams {
thread_id: subagent_thread_id.clone(),
..Default::default()
})
.await?;
let resume_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(resume_req)),
)
.await??;
let ThreadResumeResponse { thread, .. } = to_response::<ThreadResumeResponse>(resume_resp)?;
assert_eq!(thread.id, subagent_thread_id);
assert_eq!(thread.parent_thread_id, Some(parent_thread_id_str.clone()));
assert_eq!(
thread.source,
ApiSessionSource::SubAgent(SubAgentSource::Other("guardian".to_string()))
);
let turn_req = mcp
.send_turn_start_request(TurnStartParams {
thread_id: thread.id.clone(),
input: vec![V2UserInput::Text {
text: "Continue".to_string(),
text_elements: Vec::new(),
}],
..Default::default()
})
.await?;
let turn_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(turn_req)),
)
.await??;
let TurnStartResponse { turn } = to_response::<TurnStartResponse>(turn_resp)?;
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("turn/completed"),
)
.await??;
let request = response_mock.single_request();
let metadata = request
.header("x-codex-turn-metadata")
.as_deref()
.map(parse_json_header)
.unwrap_or_else(|| panic!("missing x-codex-turn-metadata header"));
assert_eq!(
metadata["parent_thread_id"].as_str(),
Some(parent_thread_id_str.as_str())
);
assert_eq!(metadata["subagent_kind"].as_str(), Some("guardian"));
assert_eq!(metadata["thread_id"].as_str(), Some(thread.id.as_str()));
assert_eq!(metadata["turn_id"].as_str(), Some(turn.id.as_str()));
assert!(metadata.get("forked_from_thread_id").is_none());
Ok(())
}
#[tokio::test]
async fn turn_steer_updates_client_metadata_on_follow_up_responses_request_v2() -> Result<()> {
skip_if_no_network!(Ok(()));
@@ -1,6 +1,8 @@
use std::borrow::Cow;
use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use anyhow::Result;
@@ -21,6 +23,8 @@ use axum::http::header::AUTHORIZATION;
use axum::routing::get;
use codex_app_server_protocol::AppInfo;
use codex_app_server_protocol::AppSummary;
use codex_app_server_protocol::AppsListParams;
use codex_app_server_protocol::AppsListResponse;
use codex_app_server_protocol::JSONRPCResponse;
use codex_app_server_protocol::PluginAuthPolicy;
use codex_app_server_protocol::PluginAvailability;
@@ -890,7 +894,7 @@ async fn plugin_install_returns_apps_needing_auth() -> Result<()> {
},
];
let tools = vec![connector_tool("beta", "Beta App")?];
let (server_url, server_handle) = start_apps_server(connectors, tools).await?;
let (server_url, server_handle, server_control) = start_apps_server(connectors, tools).await?;
let codex_home = TempDir::new()?;
write_connectors_config(codex_home.path(), &server_url)?;
@@ -918,6 +922,7 @@ async fn plugin_install_returns_apps_needing_auth() -> Result<()> {
let mut mcp = McpProcess::new(codex_home.path()).await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
let directory_requests_before_install = server_control.directory_request_count();
let request_id = mcp
.send_plugin_install_request(PluginInstallParams {
@@ -947,6 +952,7 @@ async fn plugin_install_returns_apps_needing_auth() -> Result<()> {
}],
}
);
assert!(server_control.directory_request_count() > directory_requests_before_install);
server_handle.abort();
let _ = server_handle.await;
@@ -970,7 +976,8 @@ async fn plugin_install_filters_disallowed_apps_needing_auth() -> Result<()> {
is_enabled: true,
plugin_display_names: Vec::new(),
}];
let (server_url, server_handle) = start_apps_server(connectors, Vec::new()).await?;
let (server_url, server_handle, server_control) =
start_apps_server(connectors, Vec::new()).await?;
let codex_home = TempDir::new()?;
write_connectors_config(codex_home.path(), &server_url)?;
@@ -1002,6 +1009,8 @@ async fn plugin_install_filters_disallowed_apps_needing_auth() -> Result<()> {
let mut mcp = McpProcess::new(codex_home.path()).await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
let directory_requests_before_install =
warm_app_directory_cache(&mut mcp, &server_control, "Alpha").await?;
let request_id = mcp
.send_plugin_install_request(PluginInstallParams {
@@ -1031,6 +1040,10 @@ async fn plugin_install_filters_disallowed_apps_needing_auth() -> Result<()> {
}],
}
);
assert_eq!(
server_control.directory_request_count(),
directory_requests_before_install
);
server_handle.abort();
let _ = server_handle.await;
@@ -1113,6 +1126,46 @@ async fn plugin_install_makes_bundled_mcp_servers_available_to_followup_requests
#[derive(Clone)]
struct AppsServerState {
response: Arc<StdMutex<serde_json::Value>>,
directory_request_count: Arc<AtomicUsize>,
}
#[derive(Clone)]
struct AppsServerControl {
directory_request_count: Arc<AtomicUsize>,
}
impl AppsServerControl {
fn directory_request_count(&self) -> usize {
self.directory_request_count.load(Ordering::SeqCst)
}
}
async fn warm_app_directory_cache(
mcp: &mut McpProcess,
server_control: &AppsServerControl,
expected_app_name: &str,
) -> Result<usize> {
let app_list_request_id = mcp
.send_apps_list_request(AppsListParams {
force_refetch: true,
..Default::default()
})
.await?;
let response: JSONRPCResponse = timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(app_list_request_id)),
)
.await??;
let response: AppsListResponse = to_response(response)?;
assert!(
response
.data
.iter()
.any(|app| app.name == expected_app_name)
);
let directory_request_count = server_control.directory_request_count();
assert!(directory_request_count > 0);
Ok(directory_request_count)
}
#[derive(Clone)]
@@ -1149,12 +1202,17 @@ impl ServerHandler for PluginInstallMcpServer {
async fn start_apps_server(
connectors: Vec<AppInfo>,
tools: Vec<Tool>,
) -> Result<(String, JoinHandle<()>)> {
) -> Result<(String, JoinHandle<()>, AppsServerControl)> {
let directory_request_count = Arc::new(AtomicUsize::new(0));
let state = Arc::new(AppsServerState {
response: Arc::new(StdMutex::new(
json!({ "apps": connectors, "next_token": null }),
)),
directory_request_count: directory_request_count.clone(),
});
let server_control = AppsServerControl {
directory_request_count,
};
let tools = Arc::new(StdMutex::new(tools));
let listener = TcpListener::bind("127.0.0.1:0").await?;
@@ -1184,7 +1242,7 @@ async fn start_apps_server(
let _ = axum::serve(listener, router).await;
});
Ok((format!("http://{addr}"), handle))
Ok((format!("http://{addr}"), handle, server_control))
}
async fn list_directory_connectors(
@@ -1192,6 +1250,8 @@ async fn list_directory_connectors(
headers: HeaderMap,
uri: Uri,
) -> Result<impl axum::response::IntoResponse, StatusCode> {
state.directory_request_count.fetch_add(1, Ordering::SeqCst);
let bearer_ok = headers
.get(AUTHORIZATION)
.and_then(|value| value.to_str().ok())
@@ -1,5 +1,6 @@
use anyhow::Result;
use app_test_support::McpProcess;
use app_test_support::create_fake_parented_rollout_with_source;
use app_test_support::create_fake_rollout;
use app_test_support::create_fake_rollout_with_source;
use app_test_support::create_final_assistant_message_sse_response;
@@ -1049,7 +1050,7 @@ async fn thread_list_filters_by_subagent_variant() -> Result<()> {
let parent_thread_id = ThreadId::from_string(&Uuid::new_v4().to_string())?;
let review_id = create_fake_rollout_with_source(
let review_id = create_fake_parented_rollout_with_source(
codex_home.path(),
"2025-02-02T09-00-00",
"2025-02-02T09:00:00Z",
@@ -1057,6 +1058,7 @@ async fn thread_list_filters_by_subagent_variant() -> Result<()> {
Some("mock_provider"),
/*git_info*/ None,
CoreSessionSource::SubAgent(SubAgentSource::Review),
parent_thread_id,
)?;
let compact_id = create_fake_rollout_with_source(
codex_home.path(),
@@ -1109,6 +1111,10 @@ async fn thread_list_filters_by_subagent_variant() -> Result<()> {
.map(|thread| thread.id.as_str())
.collect();
assert_eq!(review_ids, vec![review_id.as_str()]);
assert_eq!(
review.data[0].parent_thread_id,
Some(parent_thread_id.to_string())
);
let compact = list_threads(
&mut mcp,
@@ -1358,6 +1358,7 @@ async fn seed_pathless_store_thread(
.create_thread(CreateThreadParams {
thread_id,
forked_from_id: None,
parent_thread_id: None,
source: ProtocolSessionSource::Cli,
thread_source: None,
base_instructions: BaseInstructions::default(),
@@ -51,6 +51,7 @@ use codex_app_server_protocol::TurnStartResponse;
use codex_app_server_protocol::TurnStatus;
use codex_app_server_protocol::UserInput;
use codex_config::types::AuthCredentialsStoreMode;
use codex_core::ARCHIVED_SESSIONS_SUBDIR;
use codex_login::REFRESH_TOKEN_URL_OVERRIDE_ENV_VAR;
use codex_protocol::ThreadId;
use codex_protocol::config_types::Personality;
@@ -780,6 +781,57 @@ async fn thread_resume_can_skip_turns_for_metadata_only_resume() -> Result<()> {
Ok(())
}
#[tokio::test]
async fn thread_resume_rejects_archived_session_by_id() -> Result<()> {
let server = create_mock_responses_server_repeating_assistant("Done").await;
let codex_home = TempDir::new()?;
create_config_toml(codex_home.path(), &server.uri())?;
let filename_ts = "2025-01-05T12-00-00";
let conversation_id = create_fake_rollout_with_text_elements(
codex_home.path(),
filename_ts,
"2025-01-05T12:00:00Z",
"Archived saved user message",
Vec::new(),
Some("mock_provider"),
/*git_info*/ None,
)?;
let active_rollout_path = rollout_path(codex_home.path(), filename_ts, &conversation_id);
let archived_dir = codex_home.path().join(ARCHIVED_SESSIONS_SUBDIR);
std::fs::create_dir_all(&archived_dir)?;
std::fs::rename(
&active_rollout_path,
archived_dir.join(active_rollout_path.file_name().expect("rollout file name")),
)?;
let mut mcp = McpProcess::new(codex_home.path()).await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let resume_id = mcp
.send_thread_resume_request(ThreadResumeParams {
thread_id: conversation_id.clone(),
..Default::default()
})
.await?;
let resume_err: JSONRPCError = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_error_message(RequestId::Integer(resume_id)),
)
.await??;
let message = resume_err.error.message;
assert!(
message.contains(&format!("session {conversation_id} is archived"))
&& message.contains(&format!(
"codex unarchive {conversation_id}` to unarchive it first"
)),
"unexpected resume error: {message}"
);
Ok(())
}
#[tokio::test]
async fn thread_resume_keeps_paused_goal_paused() -> Result<()> {
let server = create_mock_responses_server_repeating_assistant("Done").await;
@@ -1739,6 +1791,7 @@ stream_max_retries = 0
let session_meta = SessionMeta {
id: conversation_id,
forked_from_id: None,
parent_thread_id: None,
timestamp: "2025-01-05T12:00:00Z".to_string(),
cwd: repo_path.clone(),
originator: "codex".to_string(),
@@ -211,6 +211,7 @@ async fn thread_unarchive_preserves_pathless_store_metadata() -> Result<()> {
.create_thread(CreateThreadParams {
thread_id,
forked_from_id: Some(parent_thread_id),
parent_thread_id: None,
source: SessionSource::Cli,
thread_source: None,
base_instructions: BaseInstructions::default(),
@@ -7,13 +7,19 @@ use app_test_support::ChatGptAuthFixture;
use app_test_support::McpProcess;
use app_test_support::to_response;
use app_test_support::write_chatgpt_auth;
use codex_app_server_protocol::ItemCompletedNotification;
use codex_app_server_protocol::ItemStartedNotification;
use codex_app_server_protocol::JSONRPCResponse;
use codex_app_server_protocol::RequestId;
use codex_app_server_protocol::ThreadItem;
use codex_app_server_protocol::ThreadReadParams;
use codex_app_server_protocol::ThreadReadResponse;
use codex_app_server_protocol::ThreadStartParams;
use codex_app_server_protocol::ThreadStartResponse;
use codex_app_server_protocol::TurnStartParams;
use codex_app_server_protocol::TurnStartResponse;
use codex_app_server_protocol::UserInput as V2UserInput;
use codex_app_server_protocol::WebSearchAction;
use codex_config::types::AuthCredentialsStoreMode;
use core_test_support::responses;
use pretty_assertions::assert_eq;
@@ -84,10 +90,11 @@ async fn standalone_web_search_round_trips_encrypted_output() -> Result<()> {
)
.await??;
let ThreadStartResponse { thread, .. } = to_response::<ThreadStartResponse>(thread_resp)?;
let thread_id = thread.id.clone();
let turn_req = mcp
.send_turn_start_request(TurnStartParams {
thread_id: thread.id,
thread_id: thread_id.clone(),
client_user_message_id: None,
input: vec![V2UserInput::Text {
text: "Search the web".to_string(),
@@ -103,6 +110,13 @@ async fn standalone_web_search_round_trips_encrypted_output() -> Result<()> {
.await??;
let _turn: TurnStartResponse = to_response::<TurnStartResponse>(turn_resp)?;
let started = timeout(DEFAULT_READ_TIMEOUT, wait_for_web_search_started(&mut mcp)).await??;
let completed = timeout(
DEFAULT_READ_TIMEOUT,
wait_for_web_search_completed(&mut mcp),
)
.await??;
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("turn/completed"),
@@ -126,6 +140,7 @@ async fn standalone_web_search_round_trips_encrypted_output() -> Result<()> {
);
let search_body = search_request_body(&server).await?;
assert_eq!(search_body["model"], json!("mock-model"));
assert_eq!(
search_body["commands"],
json!({
@@ -159,10 +174,83 @@ async fn standalone_web_search_round_trips_encrypted_output() -> Result<()> {
}],
})
);
assert_eq!(
started.item,
ThreadItem::WebSearch {
id: call_id.to_string(),
query: String::new(),
action: Some(WebSearchAction::Other),
}
);
let expected_completed_item = ThreadItem::WebSearch {
id: call_id.to_string(),
query: "standalone web search".to_string(),
action: Some(WebSearchAction::Search {
query: Some("standalone web search".to_string()),
queries: None,
}),
};
assert_eq!(completed.item, expected_completed_item);
drop(mcp);
let mut reloaded_mcp =
McpProcess::new_with_env(codex_home.path(), &[("OPENAI_API_KEY", None)]).await?;
timeout(DEFAULT_READ_TIMEOUT, reloaded_mcp.initialize()).await??;
let read_req = reloaded_mcp
.send_thread_read_request(ThreadReadParams {
thread_id,
include_turns: true,
})
.await?;
let read_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
reloaded_mcp.read_stream_until_response_message(RequestId::Integer(read_req)),
)
.await??;
let ThreadReadResponse { thread, .. } = to_response::<ThreadReadResponse>(read_resp)?;
let persisted_web_searches: Vec<&ThreadItem> = thread
.turns
.iter()
.flat_map(|turn| &turn.items)
.filter(|item| matches!(item, ThreadItem::WebSearch { .. }))
.collect();
assert_eq!(persisted_web_searches, vec![&expected_completed_item]);
Ok(())
}
async fn wait_for_web_search_started(mcp: &mut McpProcess) -> Result<ItemStartedNotification> {
loop {
let notification = mcp
.read_stream_until_notification_message("item/started")
.await?;
let started: ItemStartedNotification = serde_json::from_value(
notification
.params
.context("item/started notification should include params")?,
)?;
if matches!(&started.item, ThreadItem::WebSearch { .. }) {
return Ok(started);
}
}
}
async fn wait_for_web_search_completed(mcp: &mut McpProcess) -> Result<ItemCompletedNotification> {
loop {
let notification = mcp
.read_stream_until_notification_message("item/completed")
.await?;
let completed: ItemCompletedNotification = serde_json::from_value(
notification
.params
.context("item/completed notification should include params")?,
)?;
if matches!(&completed.item, ThreadItem::WebSearch { .. }) {
return Ok(completed);
}
}
}
async fn mount_search_response(server: &MockServer) {
Mock::given(method("POST"))
.and(path("/api/codex/alpha/search"))
+18
View File
@@ -1,4 +1,5 @@
use crate::types::CodeTaskDetailsResponse;
use crate::types::ConfigBundleResponse;
use crate::types::ConfigFileResponse;
use crate::types::PaginatedListTaskListItem;
use crate::types::RateLimitReachedKind as BackendRateLimitReachedKind;
@@ -408,6 +409,23 @@ impl Client {
.map_err(RequestError::from)
}
/// Fetch the selected cloud-managed config bundle from codex-backend.
///
/// `GET /api/codex/config/bundle` (Codex API style) or
/// `GET /wham/config/bundle` (ChatGPT backend-api style).
pub async fn get_config_bundle(
&self,
) -> std::result::Result<ConfigBundleResponse, RequestError> {
let url = match self.path_style {
PathStyle::CodexApi => format!("{}/api/codex/config/bundle", self.base_url),
PathStyle::ChatGptApi => format!("{}/wham/config/bundle", self.base_url),
};
let req = self.http.get(&url).headers(self.headers());
let (body, ct) = self.exec_request_detailed(req, "GET", &url).await?;
self.decode_json::<ConfigBundleResponse>(&url, &ct, &body)
.map_err(RequestError::from)
}
/// Create a new task (user turn) by POSTing to the appropriate backend path
/// based on `path_style`. Returns the created task id.
pub async fn create_task(&self, request_body: serde_json::Value) -> Result<String> {
+4
View File
@@ -6,7 +6,11 @@ pub use client::Client;
pub use client::RequestError;
pub use types::CodeTaskDetailsResponse;
pub use types::CodeTaskDetailsResponseExt;
pub use types::ConfigBundleResponse;
pub use types::ConfigFileResponse;
pub use types::DeliveredConfigToml;
pub use types::DeliveredRequirementsToml;
pub use types::DeliveredTomlFragment;
pub use types::PaginatedListTaskListItem;
pub use types::TaskListItem;
pub use types::TurnAttemptsSiblingTurnsResponse;
+4
View File
@@ -1,5 +1,9 @@
pub use codex_backend_openapi_models::models::ConfigBundleResponse;
pub use codex_backend_openapi_models::models::ConfigFileResponse;
pub use codex_backend_openapi_models::models::CreditStatusDetails;
pub use codex_backend_openapi_models::models::DeliveredConfigToml;
pub use codex_backend_openapi_models::models::DeliveredRequirementsToml;
pub use codex_backend_openapi_models::models::DeliveredTomlFragment;
pub use codex_backend_openapi_models::models::PaginatedListTaskListItem;
pub use codex_backend_openapi_models::models::PlanType;
pub use codex_backend_openapi_models::models::RateLimitReachedKind;
+242 -32
View File
@@ -35,6 +35,7 @@ use codex_tui::UpdateAction;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_cli::CliConfigOverrides;
use codex_utils_cli::ProfileV2Name;
use codex_utils_cli::SharedCliOptions;
use codex_utils_cli::resume_hint;
use owo_colors::OwoColorize;
use std::io::IsTerminal;
@@ -50,6 +51,8 @@ mod marketplace_cmd;
mod mcp_cmd;
mod plugin_cmd;
mod remote_control_cmd;
#[cfg(target_os = "windows")]
mod sandbox_setup;
mod state_db_recovery;
#[cfg(not(windows))]
mod wsl_paths;
@@ -173,6 +176,12 @@ enum Subcommand {
/// Resume a previous interactive session (picker by default; use --last to continue the most recent).
Resume(ResumeCommand),
/// Archive a saved session by id or session name.
Archive(SessionArchiveCommand),
/// Unarchive a saved session by id or session name.
Unarchive(SessionArchiveCommand),
/// Fork a previous interactive session (picker by default; use --last to fork the most recent).
Fork(ForkCommand),
@@ -294,7 +303,7 @@ struct DebugTraceReduceCommand {
#[derive(Debug, Parser)]
struct ResumeCommand {
/// Conversation/session id (UUID) or thread name. UUIDs take precedence if it parses.
/// Session id (UUID) or session name. UUIDs take precedence if it parses.
/// If omitted, use --last to pick the most recent recorded session.
#[arg(value_name = "SESSION_ID")]
session_id: Option<String>,
@@ -318,6 +327,32 @@ struct ResumeCommand {
config_overrides: TuiCli,
}
#[derive(Debug, Parser)]
struct SessionArchiveCommand {
/// Session id (UUID) or session name. UUIDs take precedence if it parses.
#[arg(value_name = "SESSION")]
target: String,
#[clap(flatten)]
remote: InteractiveRemoteOptions,
#[clap(flatten)]
config_overrides: SessionArchiveConfigOverrides,
}
#[derive(Debug, Args, Clone, Default)]
struct SessionArchiveConfigOverrides {
#[clap(flatten)]
shared: SharedCliOptions,
/// Error out when config.toml contains fields that are not recognized by this version of Codex.
#[arg(long = "strict-config", default_value_t = false)]
strict_config: bool,
#[clap(flatten)]
config_overrides: CliConfigOverrides,
}
#[derive(Debug, Parser)]
struct ForkCommand {
/// Conversation/session id (UUID). When provided, forks this session.
@@ -734,6 +769,39 @@ fn run_execpolicycheck(cmd: ExecPolicyCheckCommand) -> anyhow::Result<()> {
cmd.run()
}
async fn run_session_archive_cli_command(
action: codex_tui::SessionArchiveAction,
cmd: SessionArchiveCommand,
mut interactive: TuiCli,
root_config_overrides: CliConfigOverrides,
root_remote: Option<String>,
root_remote_auth_token_env: Option<String>,
arg0_paths: Arg0DispatchPaths,
) -> anyhow::Result<String> {
let SessionArchiveCommand {
target,
remote,
config_overrides,
} = cmd;
interactive =
finalize_session_archive_interactive(interactive, root_config_overrides, config_overrides);
let explicit_remote_endpoint = resolve_remote_endpoint(
remote.remote.or(root_remote),
remote.remote_auth_token_env.or(root_remote_auth_token_env),
)?;
codex_tui::run_session_archive_command(
action,
target,
codex_tui::SessionArchiveCommandOptions {
cli: interactive,
arg0_paths,
explicit_remote_endpoint,
},
)
.await
.map_err(|err| anyhow::anyhow!("{err}"))
}
async fn run_debug_app_server_command(cmd: DebugAppServerCommand) -> anyhow::Result<()> {
match cmd.subcommand {
DebugAppServerSubcommand::SendMessageV2(cmd) => {
@@ -1124,6 +1192,32 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> {
.await?;
handle_app_exit(exit_info)?;
}
Some(Subcommand::Archive(cmd)) => {
let output = run_session_archive_cli_command(
codex_tui::SessionArchiveAction::Archive,
cmd,
interactive,
root_config_overrides.clone(),
root_remote.clone(),
root_remote_auth_token_env.clone(),
arg0_paths.clone(),
)
.await?;
println!("{output}");
}
Some(Subcommand::Unarchive(cmd)) => {
let output = run_session_archive_cli_command(
codex_tui::SessionArchiveAction::Unarchive,
cmd,
interactive,
root_config_overrides.clone(),
root_remote.clone(),
root_remote_auth_token_env.clone(),
arg0_paths.clone(),
)
.await?;
println!("{output}");
}
Some(Subcommand::Fork(ForkCommand {
session_id,
last,
@@ -1250,6 +1344,16 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> {
.await?;
}
Some(Subcommand::Sandbox(mut sandbox_cli)) => {
#[cfg(target_os = "windows")]
if let Some(setup_cli) = sandbox_setup::parse_setup_command(&sandbox_cli.command)? {
reject_remote_mode_for_subcommand(
root_remote.as_deref(),
root_remote_auth_token_env.as_deref(),
"sandbox setup",
)?;
sandbox_setup::run(setup_cli).await?;
return Ok(());
}
reject_remote_mode_for_subcommand(
root_remote.as_deref(),
root_remote_auth_token_env.as_deref(),
@@ -1463,6 +1567,8 @@ fn profile_v2_for_subcommand<'a>(
Subcommand::Exec(_)
| Subcommand::Review(_)
| Subcommand::Resume(_)
| Subcommand::Archive(_)
| Subcommand::Unarchive(_)
| Subcommand::Fork(_)
| Subcommand::Mcp(_)
| Subcommand::Sandbox(_)
@@ -1470,7 +1576,7 @@ fn profile_v2_for_subcommand<'a>(
subcommand: DebugSubcommand::PromptInput(_),
}) => Ok(Some(profile_v2)),
_ => anyhow::bail!(
"--profile only applies to runtime commands and `codex mcp`: `codex`, `codex exec`, `codex review`, `codex resume`, `codex fork`, `codex mcp`, `codex sandbox`, and `codex debug prompt-input`."
"--profile only applies to runtime commands and `codex mcp`: `codex`, `codex exec`, `codex review`, `codex resume`, `codex archive`, `codex unarchive`, `codex fork`, `codex mcp`, `codex sandbox`, and `codex debug prompt-input`."
),
}
}
@@ -1890,6 +1996,8 @@ fn unsupported_subcommand_name_for_strict_config(
| Some(Subcommand::McpServer(_))
| Some(Subcommand::ExecServer(_))
| Some(Subcommand::Resume(_))
| Some(Subcommand::Archive(_))
| Some(Subcommand::Unarchive(_))
| Some(Subcommand::Fork(_))
| Some(Subcommand::Doctor(_)) => None,
Some(Subcommand::AppServer(app_server)) if app_server.subcommand.is_none() => None,
@@ -2037,34 +2145,13 @@ async fn run_interactive_tui(
}
}
let mut remote_endpoint = remote
.as_deref()
.map(codex_tui::resolve_remote_addr)
.transpose()
.map_err(std::io::Error::other)?;
if let Some(remote_auth_token_env) = remote_auth_token_env {
let Some(endpoint) = remote_endpoint.as_mut() else {
return Ok(AppExitInfo::fatal(
"`--remote-auth-token-env` requires `--remote`.",
));
};
if !codex_tui::remote_addr_supports_auth_token(endpoint) {
return Ok(AppExitInfo::fatal(
"`--remote-auth-token-env` requires a `wss://` or loopback `ws://` remote.",
));
let remote_endpoint = match resolve_remote_endpoint(remote, remote_auth_token_env) {
Ok(remote_endpoint) => remote_endpoint,
Err(err) if is_remote_auth_usage_error(&err) => {
return Ok(AppExitInfo::fatal(err.to_string()));
}
let auth_token = read_remote_auth_token_from_env_var(&remote_auth_token_env)
.map_err(std::io::Error::other)?;
let codex_tui::RemoteAppServerEndpoint::WebSocket {
auth_token: slot, ..
} = endpoint
else {
return Ok(AppExitInfo::fatal(
"`--remote-auth-token-env` requires a `wss://` or loopback `ws://` remote.",
));
};
*slot = Some(auth_token);
}
Err(err) => return Err(err),
};
let start_tui = || {
codex_tui::run_main(
interactive.clone(),
@@ -2108,6 +2195,46 @@ async fn run_interactive_tui(
}
}
fn resolve_remote_endpoint(
remote: Option<String>,
remote_auth_token_env: Option<String>,
) -> std::io::Result<Option<codex_tui::RemoteAppServerEndpoint>> {
let mut remote_endpoint = remote
.as_deref()
.map(codex_tui::resolve_remote_addr)
.transpose()
.map_err(std::io::Error::other)?;
if let Some(remote_auth_token_env) = remote_auth_token_env {
let Some(endpoint) = remote_endpoint.as_mut() else {
return Err(std::io::Error::other(
"`--remote-auth-token-env` requires `--remote`.",
));
};
if !codex_tui::remote_addr_supports_auth_token(endpoint) {
return Err(std::io::Error::other(
"`--remote-auth-token-env` requires a `wss://` or loopback `ws://` remote.",
));
}
let auth_token = read_remote_auth_token_from_env_var(&remote_auth_token_env)
.map_err(std::io::Error::other)?;
let codex_tui::RemoteAppServerEndpoint::WebSocket {
auth_token: slot, ..
} = endpoint
else {
return Err(std::io::Error::other(
"`--remote-auth-token-env` requires a `wss://` or loopback `ws://` remote.",
));
};
*slot = Some(auth_token);
}
Ok(remote_endpoint)
}
fn is_remote_auth_usage_error(err: &std::io::Error) -> bool {
err.to_string()
.starts_with("`--remote-auth-token-env` requires")
}
fn confirm(prompt: &str) -> std::io::Result<bool> {
eprintln!("{prompt}");
@@ -2171,9 +2298,31 @@ fn finalize_fork_interactive(
interactive
}
/// Merge flags provided to `codex resume`/`codex fork` so they take precedence over any
/// root-level flags. Only overrides fields explicitly set on the subcommand-scoped
/// CLI. Also appends `-c key=value` overrides with highest precedence.
fn finalize_session_archive_interactive(
mut interactive: TuiCli,
root_config_overrides: CliConfigOverrides,
archive_cli: SessionArchiveConfigOverrides,
) -> TuiCli {
let SessionArchiveConfigOverrides {
shared,
strict_config,
config_overrides,
} = archive_cli;
interactive.shared.apply_subcommand_overrides(shared);
if strict_config {
interactive.strict_config = true;
}
interactive
.config_overrides
.raw_overrides
.extend(config_overrides.raw_overrides);
prepend_config_flags(&mut interactive.config_overrides, root_config_overrides);
interactive
}
/// Merge flags provided to runtime wrapper commands so they take precedence over any root-level
/// flags. Only overrides fields explicitly set on the subcommand-scoped CLI. Also appends
/// `-c key=value` overrides with highest precedence.
fn merge_interactive_cli_flags(interactive: &mut TuiCli, subcommand_cli: TuiCli) {
let TuiCli {
shared,
@@ -2335,6 +2484,32 @@ mod tests {
finalize_fork_interactive(interactive, root_overrides, session_id, last, all, fork_cli)
}
fn finalize_archive_from_args(args: &[&str]) -> (String, TuiCli, InteractiveRemoteOptions) {
let cli = MultitoolCli::try_parse_from(args).expect("parse");
let MultitoolCli {
interactive,
config_overrides: root_overrides,
subcommand,
feature_toggles: _,
remote: _,
} = cli;
let Subcommand::Archive(SessionArchiveCommand {
target,
remote,
config_overrides: archive_cli,
}) = subcommand.expect("archive present")
else {
unreachable!()
};
(
target,
finalize_session_archive_interactive(interactive, root_overrides, archive_cli),
remote,
)
}
fn profile_v2_for_args(args: &[&str]) -> anyhow::Result<Option<String>> {
let cli = MultitoolCli::try_parse_from(args).expect("parse");
let Some(subcommand) = cli.subcommand.as_ref() else {
@@ -2605,6 +2780,41 @@ mod tests {
assert!(matches!(cli.subcommand, Some(Subcommand::Update)));
}
#[test]
fn archive_merges_scoped_tui_flags() {
let (target, interactive, remote) = finalize_archive_from_args(
[
"codex",
"-C",
"/root",
"archive",
"--remote",
"unix://archive.sock",
"--strict-config",
"--dangerously-bypass-hook-trust",
"-m",
"gpt-5.1-test",
"-p",
"work",
"-C",
"/archive",
"my-thread",
]
.as_ref(),
);
assert_eq!(target, "my-thread");
assert_eq!(remote.remote.as_deref(), Some("unix://archive.sock"));
assert_eq!(interactive.model.as_deref(), Some("gpt-5.1-test"));
assert_eq!(interactive.config_profile_v2.as_deref(), Some("work"));
assert_eq!(
interactive.cwd.as_deref(),
Some(std::path::Path::new("/archive"))
);
assert!(interactive.strict_config);
assert!(interactive.bypass_hook_trust);
}
#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]
#[test]
fn sandbox_parses_permissions_profile() {
+206
View File
@@ -0,0 +1,206 @@
use std::path::PathBuf;
use clap::ArgAction;
use clap::ArgGroup;
use clap::Parser;
use codex_core::config::edit::ConfigEditsBuilder;
use codex_core::config::find_codex_home;
#[derive(Debug, Parser)]
#[command(group(
ArgGroup::new("sandbox_user")
.required(true)
.args(["user", "current_user"])
))]
pub(crate) struct SandboxSetupCommand {
/// Set up the elevated Windows sandbox.
#[arg(long = "elevated", action = ArgAction::SetTrue)]
elevated_sandbox_level: bool,
/// Windows user that will run Codex after managed deployment.
#[arg(
long = "user",
value_name = "USER",
conflicts_with = "current_user",
requires = "codex_home"
)]
user: Option<String>,
/// Use the current Windows user as the Codex user.
#[arg(
long = "current-user",
default_value_t = false,
conflicts_with = "user"
)]
current_user: bool,
/// CODEX_HOME for the Codex user. Required with --user.
#[arg(long = "codex-home", value_name = "DIR")]
codex_home: Option<PathBuf>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SandboxSetupLevel {
Elevated,
}
impl SandboxSetupCommand {
fn setup_level(&self) -> anyhow::Result<SandboxSetupLevel> {
if self.elevated_sandbox_level {
Ok(SandboxSetupLevel::Elevated)
} else {
anyhow::bail!("`codex sandbox setup` currently requires --elevated");
}
}
}
pub(crate) async fn run(cmd: SandboxSetupCommand) -> anyhow::Result<()> {
match cmd.setup_level()? {
SandboxSetupLevel::Elevated => run_elevated(cmd).await,
}
}
pub(crate) fn parse_setup_command(
sandbox_command: &[String],
) -> anyhow::Result<Option<SandboxSetupCommand>> {
if sandbox_command
.first()
.is_none_or(|command| command != "setup")
{
return Ok(None);
}
SandboxSetupCommand::try_parse_from(sandbox_command.iter().map(String::as_str))
.map(Some)
.map_err(anyhow::Error::from)
}
async fn run_elevated(cmd: SandboxSetupCommand) -> anyhow::Result<()> {
let identity = resolve_sandbox_setup_identity(&cmd)?;
codex_core::windows_sandbox::run_elevated_provisioning_setup(
identity.codex_home.as_path(),
identity.real_user.as_str(),
)?;
ConfigEditsBuilder::new(identity.codex_home.as_path())
.set_windows_sandbox_mode("elevated")
.apply()
.await
.map_err(|err| {
anyhow::anyhow!(
"sandbox provisioning succeeded, but failed to persist elevated sandbox config: {err}"
)
})?;
println!(
"Windows elevated sandbox setup completed for {} at {}.",
identity.real_user,
identity.codex_home.display()
);
Ok(())
}
struct SandboxSetupIdentity {
real_user: String,
codex_home: PathBuf,
}
fn resolve_sandbox_setup_identity(
cmd: &SandboxSetupCommand,
) -> anyhow::Result<SandboxSetupIdentity> {
if cmd.current_user {
let real_user = std::env::var("USERNAME")
.or_else(|_| std::env::var("USER"))
.map_err(|err| {
anyhow::anyhow!("failed to determine current user from environment: {err}")
})?;
let codex_home = match cmd.codex_home.clone() {
Some(codex_home) => codex_home,
None => find_codex_home()?.to_path_buf(),
};
return Ok(SandboxSetupIdentity {
real_user,
codex_home,
});
}
let real_user = cmd
.user
.clone()
.ok_or_else(|| anyhow::anyhow!("--user or --current-user is required"))?;
let codex_home = cmd
.codex_home
.clone()
.ok_or_else(|| anyhow::anyhow!("--codex-home is required with --user"))?;
Ok(SandboxSetupIdentity {
real_user,
codex_home,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_managed_user_identity() {
let command = SandboxSetupCommand::try_parse_from([
"setup",
"--elevated",
"--user",
"DOMAIN\\alice",
"--codex-home",
r"C:\Users\alice\.codex",
])
.expect("parse");
assert!(command.elevated_sandbox_level);
assert_eq!(command.user.as_deref(), Some(r"DOMAIN\alice"));
assert!(!command.current_user);
assert_eq!(
command.codex_home.as_deref(),
Some(std::path::Path::new(r"C:\Users\alice\.codex"))
);
}
#[test]
fn requires_explicit_user_identity() {
let err = SandboxSetupCommand::try_parse_from(["setup", "--elevated"])
.expect_err("parse should fail");
assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument);
}
#[test]
fn requires_codex_home_for_managed_user() {
let err =
SandboxSetupCommand::try_parse_from(["setup", "--elevated", "--user", "DOMAIN\\alice"])
.expect_err("parse should fail");
assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument);
}
#[test]
fn parses_setup_from_sandbox_command_args() {
let command = parse_setup_command(&[
"setup".to_string(),
"--elevated".to_string(),
"--user".to_string(),
r"DOMAIN\alice".to_string(),
"--codex-home".to_string(),
r"C:\Users\alice\.codex".to_string(),
])
.expect("parse")
.expect("setup command");
assert_eq!(command.user.as_deref(), Some(r"DOMAIN\alice"));
}
#[test]
fn ignores_non_setup_sandbox_command_args() {
let command =
parse_setup_command(&["echo".to_string(), "hello".to_string()]).expect("parse");
assert!(command.is_none());
}
}
+16
View File
@@ -1222,6 +1222,7 @@ mod tests {
allow_managed_hooks_only: None,
allow_appshots: None,
computer_use: None,
windows: None,
guardian_policy_config: None,
feature_requirements: None,
hooks: None,
@@ -1308,6 +1309,7 @@ mod tests {
allow_managed_hooks_only: None,
allow_appshots: None,
computer_use: None,
windows: None,
guardian_policy_config: None,
feature_requirements: None,
hooks: None,
@@ -1345,6 +1347,7 @@ mod tests {
allow_managed_hooks_only: None,
allow_appshots: None,
computer_use: None,
windows: None,
guardian_policy_config: None,
feature_requirements: None,
hooks: None,
@@ -1399,6 +1402,7 @@ mod tests {
allow_managed_hooks_only: None,
allow_appshots: None,
computer_use: None,
windows: None,
guardian_policy_config: None,
feature_requirements: None,
hooks: None,
@@ -1582,6 +1586,7 @@ command = "sample-mcp"
allow_managed_hooks_only: None,
allow_appshots: None,
computer_use: None,
windows: None,
guardian_policy_config: None,
feature_requirements: None,
hooks: None,
@@ -1666,6 +1671,7 @@ command = "sample-mcp"
allow_managed_hooks_only: None,
allow_appshots: None,
computer_use: None,
windows: None,
guardian_policy_config: None,
feature_requirements: None,
hooks: None,
@@ -1748,6 +1754,7 @@ command = "sample-mcp"
allow_managed_hooks_only: None,
allow_appshots: None,
computer_use: None,
windows: None,
guardian_policy_config: None,
feature_requirements: None,
hooks: None,
@@ -1958,6 +1965,7 @@ command = "sample-mcp"
allow_managed_hooks_only: None,
allow_appshots: None,
computer_use: None,
windows: None,
guardian_policy_config: None,
feature_requirements: None,
hooks: None,
@@ -2002,6 +2010,7 @@ command = "sample-mcp"
allow_managed_hooks_only: None,
allow_appshots: None,
computer_use: None,
windows: None,
guardian_policy_config: None,
feature_requirements: None,
hooks: None,
@@ -2066,6 +2075,7 @@ command = "sample-mcp"
allow_managed_hooks_only: None,
allow_appshots: None,
computer_use: None,
windows: None,
guardian_policy_config: None,
feature_requirements: None,
hooks: None,
@@ -2126,6 +2136,7 @@ command = "sample-mcp"
allow_managed_hooks_only: None,
allow_appshots: None,
computer_use: None,
windows: None,
guardian_policy_config: None,
feature_requirements: None,
hooks: None,
@@ -2188,6 +2199,7 @@ command = "sample-mcp"
allow_managed_hooks_only: None,
allow_appshots: None,
computer_use: None,
windows: None,
guardian_policy_config: None,
feature_requirements: None,
hooks: None,
@@ -2251,6 +2263,7 @@ command = "sample-mcp"
allow_managed_hooks_only: None,
allow_appshots: None,
computer_use: None,
windows: None,
guardian_policy_config: None,
feature_requirements: None,
hooks: None,
@@ -2318,6 +2331,7 @@ command = "sample-mcp"
allow_managed_hooks_only: None,
allow_appshots: None,
computer_use: None,
windows: None,
guardian_policy_config: None,
feature_requirements: None,
hooks: None,
@@ -2411,6 +2425,7 @@ command = "sample-mcp"
allow_managed_hooks_only: None,
allow_appshots: None,
computer_use: None,
windows: None,
guardian_policy_config: None,
feature_requirements: None,
hooks: None,
@@ -2450,6 +2465,7 @@ command = "sample-mcp"
allow_managed_hooks_only: None,
allow_appshots: None,
computer_use: None,
windows: None,
guardian_policy_config: None,
feature_requirements: None,
hooks: None,
-2
View File
@@ -16,8 +16,6 @@ sandbox = ["v8/v8_enable_sandbox"]
workspace = true
[dependencies]
async-channel = { workspace = true }
async-trait = { workspace = true }
codex-protocol = { workspace = true }
deno_core_icudata = { workspace = true }
serde = { workspace = true, features = ["derive"] }
+5 -5
View File
@@ -17,8 +17,8 @@ const EXEC_DESCRIPTION_TEMPLATE: &str = r#"Run JavaScript code to orchestrate/co
- Runs raw JavaScript -- no Node, no file system, no network access, no console.
- Accepts raw JavaScript source text, not JSON, quoted strings, or markdown code fences.
- You may optionally start the tool input with a first-line pragma like `// @exec: {"yield_time_ms": 10000, "max_output_tokens": 1000}`.
- `yield_time_ms` asks `exec` to yield early after that many milliseconds if the script is still running.
- `max_output_tokens` sets the token budget for direct `exec` results. By default the result is truncated to 10000 tokens.
- `yield_time_ms` asks `exec` to yield early if the script is still running. Defaults to 10000 ms.
- `max_output_tokens` sets the token budget for direct `exec` results. Defaults to 10000 tokens.
- When the JS code is fully evaluated, the isolate's lifetime ends and unawaited promises are silently discarded.
- Global helpers:
@@ -34,9 +34,9 @@ const EXEC_DESCRIPTION_TEMPLATE: &str = r#"Run JavaScript code to orchestrate/co
- `yield_control()`: yields the accumulated output to the model immediately while the script keeps running."#;
const WAIT_DESCRIPTION_TEMPLATE: &str = r#"- Use `wait` only after `exec` returns `Script running with cell ID ...`.
- `cell_id` identifies the running `exec` cell to resume.
- `yield_time_ms` controls how long to wait for more output before yielding again. If omitted, `wait` uses its default wait timeout.
- `max_tokens` limits how much new output this wait call returns.
- `terminate: true` stops the running cell instead of waiting for more output.
- `yield_time_ms` controls how long to wait for more output before yielding again. Defaults to 10000 ms.
- `max_tokens` limits how much new output this wait call returns. Defaults to 10000 tokens.
- `terminate: true` stops the running cell; false or omitted waits for output.
- `wait` returns only the new output since the last yield, or the final completion or termination result for that cell.
- If the cell is still running, `wait` may yield again with the same `cell_id`.
- If the cell has already finished, `wait` returns the completed result and closes the cell."#;
+11 -2
View File
@@ -29,9 +29,18 @@ pub use runtime::WaitOutcome;
pub use runtime::WaitRequest;
pub use runtime::WaitToPendingOutcome;
pub use runtime::WaitToPendingRequest;
pub use service::CellId;
pub use service::CodeModeService;
pub use service::CodeModeTurnHost;
pub use service::CodeModeTurnWorker;
pub use service::CodeModeSession;
pub use service::CodeModeSessionDelegate;
pub use service::CodeModeSessionProvider;
pub use service::CodeModeSessionProviderFuture;
pub use service::CodeModeSessionResultFuture;
pub use service::InProcessCodeModeSessionProvider;
pub use service::NoopCodeModeSessionDelegate;
pub use service::NotificationFuture;
pub use service::StartedCell;
pub use service::ToolInvocationFuture;
pub const PUBLIC_TOOL_NAME: &str = "exec";
pub const WAIT_TOOL_NAME: &str = "wait";
+8 -24
View File
@@ -19,6 +19,7 @@ use crate::description::EnabledToolMetadata;
use crate::description::ToolDefinition;
use crate::description::enabled_tool_metadata;
use crate::response::FunctionCallOutputContentItem;
use crate::service::CellId;
pub const DEFAULT_EXEC_YIELD_TIME_MS: u64 = 10_000;
pub const DEFAULT_WAIT_YIELD_TIME_MS: u64 = 10_000;
@@ -27,11 +28,6 @@ const EXIT_SENTINEL: &str = "__codex_code_mode_exit__";
#[derive(Clone, Debug)]
pub struct ExecuteRequest {
/// Runtime cell id for this execution.
///
/// Callers allocate this before execution so tracing, waits, and nested tool
/// calls can refer to the cell as soon as JavaScript starts.
pub cell_id: String,
pub tool_call_id: String,
pub enabled_tools: Vec<ToolDefinition>,
pub source: String,
@@ -41,14 +37,13 @@ pub struct ExecuteRequest {
#[derive(Clone, Debug)]
pub struct WaitRequest {
pub cell_id: String,
pub cell_id: CellId,
pub yield_time_ms: u64,
pub terminate: bool,
}
#[derive(Clone, Debug)]
pub struct WaitToPendingRequest {
pub cell_id: String,
pub cell_id: CellId,
}
/// Result of waiting on a code-mode cell.
@@ -73,7 +68,7 @@ pub enum ExecuteToPendingOutcome {
/// The cell is waiting for more runtime input after draining the runtime
/// input queue that was ready at the pending boundary.
Pending {
cell_id: String,
cell_id: CellId,
content_items: Vec<FunctionCallOutputContentItem>,
/// Runtime tool-call ids emitted before this paused execution frontier
/// sealed. Hosts can use these ids to drain their tool-call transport
@@ -105,15 +100,15 @@ impl From<WaitOutcome> for RuntimeResponse {
#[derive(Debug, PartialEq, Serialize)]
pub enum RuntimeResponse {
Yielded {
cell_id: String,
cell_id: CellId,
content_items: Vec<FunctionCallOutputContentItem>,
},
Terminated {
cell_id: String,
cell_id: CellId,
content_items: Vec<FunctionCallOutputContentItem>,
},
Result {
cell_id: String,
cell_id: CellId,
content_items: Vec<FunctionCallOutputContentItem>,
error_text: Option<String>,
},
@@ -126,23 +121,13 @@ pub enum RuntimeResponse {
/// if their tool-call graph requires globally unique ids.
#[derive(Debug)]
pub struct CodeModeNestedToolCall {
pub cell_id: String,
pub cell_id: CellId,
pub runtime_tool_call_id: String,
pub tool_name: ToolName,
pub tool_kind: CodeModeToolKind,
pub input: Option<JsonValue>,
}
#[derive(Debug)]
pub(crate) enum TurnMessage {
ToolCall(CodeModeNestedToolCall),
Notify {
cell_id: String,
call_id: String,
text: String,
},
}
#[derive(Debug)]
pub(crate) enum RuntimeCommand {
ToolResponse { id: String, result: JsonValue },
@@ -460,7 +445,6 @@ mod tests {
fn execute_request(source: &str) -> ExecuteRequest {
ExecuteRequest {
cell_id: "1".to_string(),
tool_call_id: "call_1".to_string(),
enabled_tools: Vec::new(),
source: source.to_string(),
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -145,7 +145,7 @@ mod tests {
.search(
&SearchRequest {
id: "search-session".to_string(),
model: Some("gpt-test".to_string()),
model: "gpt-test".to_string(),
reasoning: None,
input: Some(SearchInput::Items(vec![ResponseItem::Message {
id: None,
+1 -2
View File
@@ -7,8 +7,7 @@ use serde::Serialize;
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct SearchRequest {
pub id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub model: Option<String>,
pub model: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub reasoning: Option<Reasoning>,
#[serde(skip_serializing_if = "Option::is_none")]
@@ -98,6 +98,7 @@ async fn models_client_hits_models_endpoint() {
input_modalities: default_input_modalities(),
used_fallback_model_metadata: false,
supports_search_tool: false,
tool_mode: None,
}],
};
@@ -0,0 +1,40 @@
/*
* codex-backend
*
* codex-backend
*
* The version of the OpenAPI document: 0.0.1
*
* Generated by: https://openapi-generator.tech
*/
use crate::models;
use serde::Deserialize;
use serde::Serialize;
#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct ConfigBundleResponse {
#[serde(
rename = "config_toml",
default,
with = "::serde_with::rust::double_option",
skip_serializing_if = "Option::is_none"
)]
pub config_toml: Option<Option<Box<models::DeliveredConfigToml>>>,
#[serde(
rename = "requirements_toml",
default,
with = "::serde_with::rust::double_option",
skip_serializing_if = "Option::is_none"
)]
pub requirements_toml: Option<Option<Box<models::DeliveredRequirementsToml>>>,
}
impl ConfigBundleResponse {
pub fn new() -> ConfigBundleResponse {
ConfigBundleResponse {
config_toml: None,
requirements_toml: None,
}
}
}
@@ -0,0 +1,32 @@
/*
* codex-backend
*
* codex-backend
*
* The version of the OpenAPI document: 0.0.1
*
* Generated by: https://openapi-generator.tech
*/
use crate::models;
use serde::Deserialize;
use serde::Serialize;
#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct DeliveredConfigToml {
#[serde(
rename = "enterprise_managed",
default,
with = "::serde_with::rust::double_option",
skip_serializing_if = "Option::is_none"
)]
pub enterprise_managed: Option<Option<Vec<models::DeliveredTomlFragment>>>,
}
impl DeliveredConfigToml {
pub fn new() -> DeliveredConfigToml {
DeliveredConfigToml {
enterprise_managed: None,
}
}
}
@@ -0,0 +1,32 @@
/*
* codex-backend
*
* codex-backend
*
* The version of the OpenAPI document: 0.0.1
*
* Generated by: https://openapi-generator.tech
*/
use crate::models;
use serde::Deserialize;
use serde::Serialize;
#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct DeliveredRequirementsToml {
#[serde(
rename = "enterprise_managed",
default,
with = "::serde_with::rust::double_option",
skip_serializing_if = "Option::is_none"
)]
pub enterprise_managed: Option<Option<Vec<models::DeliveredTomlFragment>>>,
}
impl DeliveredRequirementsToml {
pub fn new() -> DeliveredRequirementsToml {
DeliveredRequirementsToml {
enterprise_managed: None,
}
}
}
@@ -0,0 +1,28 @@
/*
* codex-backend
*
* codex-backend
*
* The version of the OpenAPI document: 0.0.1
*
* Generated by: https://openapi-generator.tech
*/
use serde::Deserialize;
use serde::Serialize;
#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct DeliveredTomlFragment {
#[serde(rename = "id")]
pub id: String,
#[serde(rename = "name")]
pub name: String,
#[serde(rename = "contents")]
pub contents: String,
}
impl DeliveredTomlFragment {
pub fn new(id: String, name: String, contents: String) -> DeliveredTomlFragment {
DeliveredTomlFragment { id, name, contents }
}
}
@@ -4,9 +4,21 @@
// The process for this will change
// Config
pub(crate) mod config_bundle_response;
pub use self::config_bundle_response::ConfigBundleResponse;
pub(crate) mod config_file_response;
pub use self::config_file_response::ConfigFileResponse;
pub(crate) mod delivered_config_toml;
pub use self::delivered_config_toml::DeliveredConfigToml;
pub(crate) mod delivered_requirements_toml;
pub use self::delivered_requirements_toml::DeliveredRequirementsToml;
pub(crate) mod delivered_toml_fragment;
pub use self::delivered_toml_fragment::DeliveredTomlFragment;
// Cloud Tasks
pub(crate) mod code_task_details_response;
pub use self::code_task_details_response::CodeTaskDetailsResponse;
+108
View File
@@ -0,0 +1,108 @@
//! Conversion from cloud-delivered config TOML fragments into config stack layers.
//!
//! Backend fragments arrive in backend priority order. This module parses each
//! fragment, resolves relative path fields against the cloud config base
//! directory, and returns layers in `ConfigLayerStack` order.
use crate::ConfigLayerEntry;
use crate::ConfigLayerSource;
use crate::TomlValue;
use crate::loader::resolve_relative_paths_in_config_toml;
use codex_utils_absolute_path::AbsolutePathBuf;
use std::fmt;
use std::io;
use thiserror::Error;
/// Config fragment delivered by the cloud config bundle.
///
/// The bundle orders fragments from highest precedence to lowest precedence.
/// This module returns config layers in stack order, so callers can append the
/// result between system and user config without re-sorting.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CloudConfigFragment {
pub id: String,
pub name: String,
pub contents: String,
}
impl CloudConfigFragment {
fn source_ref(&self) -> CloudConfigFragmentSource {
CloudConfigFragmentSource {
id: self.id.clone(),
name: self.name.clone(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CloudConfigFragmentSource {
pub id: String,
pub name: String,
}
impl fmt::Display for CloudConfigFragmentSource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} ({})", self.name, self.id)
}
}
#[derive(Debug, Error, PartialEq, Eq)]
pub enum CloudConfigLayerError {
#[error("failed to parse cloud config fragment {fragment}: {message}")]
Parse {
fragment: CloudConfigFragmentSource,
message: String,
},
#[error("invalid cloud config fragment {fragment}: {message}")]
Invalid {
fragment: CloudConfigFragmentSource,
message: String,
},
}
pub fn cloud_config_layers_from_fragments(
fragments: impl IntoIterator<Item = CloudConfigFragment>,
base_dir: &AbsolutePathBuf,
) -> Result<Vec<ConfigLayerEntry>, CloudConfigLayerError> {
let mut layers = Vec::new();
for fragment in fragments {
let source_ref = fragment.source_ref();
let raw_toml = fragment.contents;
let value: TomlValue =
toml::from_str(&raw_toml).map_err(|err| CloudConfigLayerError::Parse {
fragment: source_ref.clone(),
message: err.to_string(),
})?;
let resolved =
resolve_relative_paths_in_config_toml(value, base_dir.as_path()).map_err(|err| {
CloudConfigLayerError::Invalid {
fragment: source_ref.clone(),
message: err.to_string(),
}
})?;
layers.push(ConfigLayerEntry::new_with_raw_toml(
ConfigLayerSource::EnterpriseManaged {
id: fragment.id,
name: fragment.name,
},
resolved,
raw_toml,
base_dir.clone(),
));
}
// Bundle fragments arrive highest-priority first, while ConfigLayerStack
// folds lowest-priority to highest-priority.
layers.reverse();
Ok(layers)
}
impl From<CloudConfigLayerError> for io::Error {
fn from(error: CloudConfigLayerError) -> Self {
io::Error::new(io::ErrorKind::InvalidData, error)
}
}
#[cfg(test)]
#[path = "cloud_config_layers_tests.rs"]
mod tests;
@@ -0,0 +1,210 @@
use super::*;
use crate::CONFIG_TOML_FILE;
use crate::ConfigLayerStack;
use crate::ConfigLayerStackOrdering;
use crate::ConfigRequirements;
use crate::ConfigRequirementsToml;
use crate::config_toml::ConfigToml;
use crate::first_layer_config_error_from_entries;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_absolute_path::test_support::PathBufExt;
use codex_utils_absolute_path::test_support::test_path_buf;
use pretty_assertions::assert_eq;
use std::path::Path;
fn fragment(id: &str, name: &str, contents: &str) -> CloudConfigFragment {
CloudConfigFragment {
id: id.to_string(),
name: name.to_string(),
contents: contents.to_string(),
}
}
fn toml(contents: &str) -> TomlValue {
toml::from_str(contents).expect("test TOML should parse")
}
fn base_dir() -> AbsolutePathBuf {
test_path_buf("/var/lib/codex").abs()
}
#[test]
fn layers_are_returned_in_stack_order() {
let base_dir = base_dir();
let layers = cloud_config_layers_from_fragments(
vec![
fragment("high", "High priority", "model = \"cloud-high\""),
fragment("low", "Low priority", "model_provider = \"cloud-low\""),
],
&base_dir,
)
.expect("cloud config layers should compose");
assert_eq!(
layers
.iter()
.map(|layer| layer.name.clone())
.collect::<Vec<_>>(),
vec![
ConfigLayerSource::EnterpriseManaged {
id: "low".to_string(),
name: "Low priority".to_string(),
},
ConfigLayerSource::EnterpriseManaged {
id: "high".to_string(),
name: "High priority".to_string(),
},
]
);
}
#[test]
fn enterprise_layers_precede_user_and_override_system() {
let base_dir = base_dir();
let mut layers = vec![ConfigLayerEntry::new(
ConfigLayerSource::System {
file: test_path_buf("/etc/codex/config.toml").abs(),
},
toml(
r#"
model = "system"
model_provider = "system"
review_model = "system-review"
"#,
),
)];
layers.extend(
cloud_config_layers_from_fragments(
vec![
fragment("high", "High priority", "model_provider = \"cloud-high\""),
fragment("low", "Low priority", "review_model = \"cloud-low-review\""),
],
&base_dir,
)
.expect("cloud config layers should compose"),
);
layers.push(ConfigLayerEntry::new(
ConfigLayerSource::User {
file: test_path_buf("/home/alice/.codex/config.toml").abs(),
profile: None,
},
toml("model = \"user\""),
));
let stack = ConfigLayerStack::new(
layers,
ConfigRequirements::default(),
ConfigRequirementsToml::default(),
)
.expect("stack should be ordered");
assert_eq!(
stack
.get_layers(
ConfigLayerStackOrdering::LowestPrecedenceFirst,
/*include_disabled*/ false
)
.iter()
.map(|layer| layer.name.clone())
.collect::<Vec<_>>(),
vec![
ConfigLayerSource::System {
file: test_path_buf("/etc/codex/config.toml").abs(),
},
ConfigLayerSource::EnterpriseManaged {
id: "low".to_string(),
name: "Low priority".to_string(),
},
ConfigLayerSource::EnterpriseManaged {
id: "high".to_string(),
name: "High priority".to_string(),
},
ConfigLayerSource::User {
file: test_path_buf("/home/alice/.codex/config.toml").abs(),
profile: None,
},
]
);
assert_eq!(
stack.effective_config(),
toml(
r#"
model = "user"
model_provider = "cloud-high"
review_model = "cloud-low-review"
"#,
)
);
}
#[test]
fn relative_absolute_path_fields_resolve_against_base_dir() {
let base_dir = base_dir();
let layers = cloud_config_layers_from_fragments(
vec![fragment(
"cfg_123",
"Base policy",
"model_instructions_file = \"instructions.md\"",
)],
&base_dir,
)
.expect("relative paths should match existing MDM semantics");
let path = layers[0]
.config
.get("model_instructions_file")
.and_then(TomlValue::as_str)
.expect("path should be present");
let expected =
AbsolutePathBuf::resolve_path_against_base("instructions.md", base_dir.as_path());
assert_eq!(path, expected.to_string_lossy());
}
#[test]
fn home_relative_path_fields_are_allowed_and_resolved() {
let base_dir = base_dir();
let layers = cloud_config_layers_from_fragments(
vec![fragment(
"cfg_123",
"Base policy",
"model_instructions_file = \"~/instructions.md\"",
)],
&base_dir,
)
.expect("home-relative paths should be accepted");
let path = layers[0]
.config
.get("model_instructions_file")
.and_then(TomlValue::as_str)
.expect("path should be present");
let expected =
AbsolutePathBuf::resolve_path_against_base("~/instructions.md", base_dir.as_path());
assert_eq!(path, expected.to_string_lossy());
}
#[tokio::test]
async fn raw_toml_diagnostics_use_enterprise_layer_name() {
let base_dir = base_dir();
let layers = cloud_config_layers_from_fragments(
vec![fragment(
"cfg_123",
"Base policy",
"model_instructions_file = \"instructions.md\"\nmodel = 1",
)],
&base_dir,
)
.expect("cloud config layers should parse");
let error = first_layer_config_error_from_entries::<ConfigToml>(&layers, CONFIG_TOML_FILE)
.await
.expect("invalid raw TOML should produce a layer diagnostic");
assert_eq!(
error.path,
Path::new("enterprise-managed (Base policy, cfg_123)").to_path_buf()
);
assert_eq!(error.range.start.line, 2);
assert_eq!(error.range.start.column, 9);
assert!(error.message.contains("invalid type: integer `1`"));
}
@@ -0,0 +1,31 @@
use codex_app_server_protocol::ConfigLayerSource;
pub fn format_config_layer_source(source: &ConfigLayerSource, config_toml_file: &str) -> String {
match source {
ConfigLayerSource::Mdm { domain, key } => {
format!("MDM ({domain}:{key})")
}
ConfigLayerSource::System { file } => {
format!("system ({})", file.as_path().display())
}
ConfigLayerSource::EnterpriseManaged { id, name } => {
format!("enterprise-managed ({name}, {id})")
}
ConfigLayerSource::User { file, .. } => {
format!("user ({})", file.as_path().display())
}
ConfigLayerSource::Project { dot_codex_folder } => {
format!(
"project ({}/{config_toml_file})",
dot_codex_folder.as_path().display()
)
}
ConfigLayerSource::SessionFlags => "session-flags".to_string(),
ConfigLayerSource::LegacyManagedConfigTomlFromFile { file } => {
format!("legacy managed_config.toml ({})", file.as_path().display())
}
ConfigLayerSource::LegacyManagedConfigTomlFromMdm => {
"legacy managed_config.toml (MDM)".to_string()
}
}
}
+246 -6
View File
@@ -20,17 +20,66 @@ use crate::ConstraintError;
use crate::ManagedHooksRequirementsToml;
use crate::mcp_types::AppToolApproval;
use crate::permissions_toml::PermissionProfileToml;
use crate::types::WindowsSandboxModeToml;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RequirementSource {
Unknown,
MdmManagedPreferences { domain: String, key: String },
MdmManagedPreferences {
domain: String,
key: String,
},
CloudRequirements,
SystemRequirementsToml { file: AbsolutePathBuf },
LegacyManagedConfigTomlFromFile { file: AbsolutePathBuf },
/// Multiple requirements layers contributed to the final value. Sources are
/// stored highest-priority first, matching the order surfaced in errors.
Composite {
sources: Vec<RequirementSource>,
},
/// A backend-delivered enterprise-managed layer. `id` is the stable backend
/// identifier; `name` is the admin-facing display name.
EnterpriseManaged {
id: String,
name: String,
},
SystemRequirementsToml {
file: AbsolutePathBuf,
},
LegacyManagedConfigTomlFromFile {
file: AbsolutePathBuf,
},
LegacyManagedConfigTomlFromMdm,
}
impl RequirementSource {
pub fn composite(sources: impl IntoIterator<Item = RequirementSource>) -> Self {
let mut flattened = Vec::new();
for source in sources {
source.append_to_composite(&mut flattened);
}
match flattened.len() {
0 => RequirementSource::Unknown,
1 => flattened.remove(0),
_ => RequirementSource::Composite { sources: flattened },
}
}
fn append_to_composite(self, flattened: &mut Vec<RequirementSource>) {
match self {
RequirementSource::Composite { sources } => {
for source in sources {
source.append_to_composite(flattened);
}
}
source => {
if !flattened.contains(&source) {
flattened.push(source);
}
}
}
}
}
impl fmt::Display for RequirementSource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
@@ -41,6 +90,19 @@ impl fmt::Display for RequirementSource {
RequirementSource::CloudRequirements => {
write!(f, "cloud requirements")
}
RequirementSource::Composite { sources } => {
write!(f, "requirements layers: ")?;
for (index, source) in sources.iter().enumerate() {
if index > 0 {
write!(f, ", ")?;
}
write!(f, "{source}")?;
}
Ok(())
}
RequirementSource::EnterpriseManaged { id, name } => {
write!(f, "enterprise-managed requirements {name} ({id})")
}
RequirementSource::SystemRequirementsToml { file } => {
write!(f, "{}", file.as_path().display())
}
@@ -87,6 +149,7 @@ pub struct ConfigRequirements {
pub approval_policy: ConstrainedWithSource<AskForApproval>,
pub approvals_reviewer: ConstrainedWithSource<ApprovalsReviewer>,
pub permission_profile: ConstrainedWithSource<PermissionProfile>,
pub windows_sandbox_mode: ConstrainedWithSource<Option<WindowsSandboxModeToml>>,
pub web_search_mode: ConstrainedWithSource<WebSearchMode>,
pub allow_managed_hooks_only: Option<Sourced<bool>>,
pub allow_appshots: Option<Sourced<bool>>,
@@ -120,6 +183,10 @@ impl Default for ConfigRequirements {
Constrained::allow_any(PermissionProfile::read_only()),
/*source*/ None,
),
windows_sandbox_mode: ConstrainedWithSource::new(
Constrained::allow_any(/*initial_value*/ None),
/*source*/ None,
),
web_search_mode: ConstrainedWithSource::new(
Constrained::allow_any(WebSearchMode::Cached),
/*source*/ None,
@@ -648,6 +715,17 @@ impl ComputerUseRequirementsToml {
}
}
#[derive(Deserialize, Debug, Clone, Default, PartialEq, Eq)]
pub struct WindowsRequirementsToml {
pub allowed_sandbox_implementations: Option<Vec<WindowsSandboxModeToml>>,
}
impl WindowsRequirementsToml {
pub fn is_empty(&self) -> bool {
self.allowed_sandbox_implementations.is_none()
}
}
#[derive(Deserialize, Debug, Clone, Default, PartialEq, Eq)]
pub struct FeatureRequirementsToml {
#[serde(flatten)]
@@ -754,6 +832,7 @@ pub struct ConfigRequirementsToml {
pub allow_managed_hooks_only: Option<bool>,
pub allow_appshots: Option<bool>,
pub computer_use: Option<ComputerUseRequirementsToml>,
pub windows: Option<WindowsRequirementsToml>,
#[serde(rename = "features", alias = "feature_requirements")]
pub feature_requirements: Option<FeatureRequirementsToml>,
pub hooks: Option<ManagedHooksRequirementsToml>,
@@ -806,6 +885,7 @@ pub struct ConfigRequirementsWithSources {
pub allow_managed_hooks_only: Option<Sourced<bool>>,
pub allow_appshots: Option<Sourced<bool>>,
pub computer_use: Option<Sourced<ComputerUseRequirementsToml>>,
pub windows: Option<Sourced<WindowsRequirementsToml>>,
pub feature_requirements: Option<Sourced<FeatureRequirementsToml>>,
pub hooks: Option<Sourced<ManagedHooksRequirementsToml>>,
pub mcp_servers: Option<Sourced<BTreeMap<String, McpServerRequirement>>>,
@@ -846,6 +926,7 @@ impl ConfigRequirementsWithSources {
allow_managed_hooks_only: _,
allow_appshots: _,
computer_use: _,
windows: _,
feature_requirements: _,
hooks: _,
mcp_servers: _,
@@ -879,6 +960,7 @@ impl ConfigRequirementsWithSources {
allow_managed_hooks_only,
allow_appshots,
computer_use,
windows,
feature_requirements,
hooks,
mcp_servers,
@@ -910,6 +992,7 @@ impl ConfigRequirementsWithSources {
allow_managed_hooks_only,
allow_appshots,
computer_use,
windows,
feature_requirements,
hooks,
mcp_servers,
@@ -931,6 +1014,7 @@ impl ConfigRequirementsWithSources {
allow_managed_hooks_only: allow_managed_hooks_only.map(|sourced| sourced.value),
allow_appshots: allow_appshots.map(|sourced| sourced.value),
computer_use: computer_use.map(|sourced| sourced.value),
windows: windows.map(|sourced| sourced.value),
feature_requirements: feature_requirements.map(|sourced| sourced.value),
hooks: hooks.map(|sourced| sourced.value),
mcp_servers: mcp_servers.map(|sourced| sourced.value),
@@ -960,7 +1044,7 @@ fn hostname_matches_any_pattern(hostname: &str, patterns: &[String]) -> bool {
/// Currently, `external-sandbox` is not supported in config.toml, but it is
/// supported through programmatic use.
#[derive(Deserialize, Debug, Clone, Copy, PartialEq)]
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
pub enum SandboxModeRequirement {
#[serde(rename = "read-only")]
ReadOnly,
@@ -1021,6 +1105,10 @@ impl ConfigRequirementsToml {
.computer_use
.as_ref()
.is_none_or(ComputerUseRequirementsToml::is_empty)
&& self
.windows
.as_ref()
.is_none_or(WindowsRequirementsToml::is_empty)
&& self
.feature_requirements
.as_ref()
@@ -1065,6 +1153,7 @@ impl TryFrom<ConfigRequirementsWithSources> for ConfigRequirements {
allow_managed_hooks_only,
allow_appshots,
computer_use,
windows,
feature_requirements,
hooks,
mcp_servers,
@@ -1174,6 +1263,44 @@ impl TryFrom<ConfigRequirementsWithSources> for ConfigRequirements {
/*source*/ None,
),
};
let windows_sandbox_mode = match windows {
Some(Sourced {
value:
WindowsRequirementsToml {
allowed_sandbox_implementations: Some(implementations),
},
source: requirement_source,
}) => {
if implementations.is_empty() {
return Err(ConstraintError::empty_field(
"windows.allowed_sandbox_implementations",
));
}
// Prefer elevated when both Windows sandbox implementations are allowed.
let initial_value = if implementations.contains(&WindowsSandboxModeToml::Elevated) {
WindowsSandboxModeToml::Elevated
} else {
WindowsSandboxModeToml::Unelevated
};
let requirement_source_for_error = requirement_source.clone();
let constrained =
Constrained::new(Some(initial_value), move |candidate| match candidate {
Some(candidate) if implementations.contains(candidate) => Ok(()),
_ => Err(ConstraintError::InvalidValue {
field_name: "windows.sandbox",
candidate: format!("{candidate:?}"),
allowed: format!("{implementations:?}"),
requirement_source: requirement_source_for_error.clone(),
}),
})?;
ConstrainedWithSource::new(constrained, Some(requirement_source))
}
Some(_) | None => ConstrainedWithSource::new(
Constrained::allow_any(/*initial_value*/ None),
/*source*/ None,
),
};
let exec_policy = match rules {
Some(Sourced { value, source }) => {
let policy = value.to_requirements_policy().map_err(|err| {
@@ -1299,6 +1426,7 @@ impl TryFrom<ConfigRequirementsWithSources> for ConfigRequirements {
approval_policy,
approvals_reviewer,
permission_profile,
windows_sandbox_mode,
web_search_mode,
allow_managed_hooks_only,
allow_appshots,
@@ -1363,6 +1491,41 @@ mod tests {
)?)
}
#[test]
fn composite_requirement_source_flattens_and_deduplicates_sources() {
let mdm_source = RequirementSource::MdmManagedPreferences {
domain: "com.openai.codex".to_string(),
key: "requirements_toml_base64".to_string(),
};
let legacy_source = RequirementSource::LegacyManagedConfigTomlFromMdm;
assert_eq!(
RequirementSource::composite([
mdm_source.clone(),
RequirementSource::composite([legacy_source.clone(), mdm_source.clone()]),
]),
RequirementSource::Composite {
sources: vec![mdm_source, legacy_source],
}
);
}
#[test]
fn composite_requirement_source_display_lists_sources_in_priority_order() {
let source = RequirementSource::composite([
RequirementSource::MdmManagedPreferences {
domain: "com.openai.codex".to_string(),
key: "requirements_toml_base64".to_string(),
},
RequirementSource::LegacyManagedConfigTomlFromMdm,
]);
assert_eq!(
source.to_string(),
"requirements layers: MDM com.openai.codex:requirements_toml_base64, MDM managed_config.toml (legacy)"
);
}
fn with_unknown_source(toml: ConfigRequirementsToml) -> ConfigRequirementsWithSources {
let ConfigRequirementsToml {
allowed_approval_policies,
@@ -1374,6 +1537,7 @@ mod tests {
allow_managed_hooks_only,
allow_appshots,
computer_use,
windows,
feature_requirements,
hooks,
mcp_servers,
@@ -1401,6 +1565,7 @@ mod tests {
allow_appshots: allow_appshots
.map(|value| Sourced::new(value, RequirementSource::Unknown)),
computer_use: computer_use.map(|value| Sourced::new(value, RequirementSource::Unknown)),
windows: windows.map(|value| Sourced::new(value, RequirementSource::Unknown)),
feature_requirements: feature_requirements
.map(|value| Sourced::new(value, RequirementSource::Unknown)),
hooks: hooks.map(|value| Sourced::new(value, RequirementSource::Unknown)),
@@ -1581,6 +1746,7 @@ mod tests {
allow_managed_hooks_only: Some(true),
allow_appshots: Some(false),
computer_use: Some(computer_use.clone()),
windows: None,
feature_requirements: Some(feature_requirements.clone()),
hooks: None,
mcp_servers: None,
@@ -1621,6 +1787,7 @@ mod tests {
)),
allow_appshots: Some(Sourced::new(/*value*/ false, enforce_source.clone(),)),
computer_use: Some(Sourced::new(computer_use, enforce_source.clone())),
windows: None,
feature_requirements: Some(Sourced::new(
feature_requirements,
enforce_source.clone(),
@@ -1667,6 +1834,7 @@ mod tests {
allow_managed_hooks_only: None,
allow_appshots: None,
computer_use: None,
windows: None,
feature_requirements: None,
hooks: None,
mcp_servers: None,
@@ -1718,6 +1886,7 @@ mod tests {
allow_managed_hooks_only: None,
allow_appshots: None,
computer_use: None,
windows: None,
feature_requirements: None,
hooks: None,
mcp_servers: None,
@@ -2200,14 +2369,20 @@ allowed_approvals_reviewers = ["user"]
}
#[test]
fn constraint_error_includes_cloud_requirements_source() -> Result<()> {
fn constraint_error_includes_composite_requirement_source() -> Result<()> {
let source: ConfigRequirementsToml = from_str(
r#"
allowed_approval_policies = ["on-request"]
"#,
)?;
let source_location = RequirementSource::CloudRequirements;
let source_location = RequirementSource::composite([
RequirementSource::MdmManagedPreferences {
domain: "com.openai.codex".to_string(),
key: "requirements_toml_base64".to_string(),
},
RequirementSource::LegacyManagedConfigTomlFromMdm,
]);
let mut target = ConfigRequirementsWithSources::default();
target.merge_unset_fields(source_location.clone(), source);
@@ -2357,6 +2532,71 @@ allowed_approvals_reviewers = ["user"]
Ok(())
}
#[test]
fn deserialize_allowed_windows_sandbox_implementations() -> Result<()> {
let toml_str = r#"
[windows]
allowed_sandbox_implementations = ["elevated"]
"#;
let config: ConfigRequirementsToml = from_str(toml_str)?;
let requirements: ConfigRequirements = with_unknown_source(config).try_into()?;
assert_eq!(
requirements.windows_sandbox_mode.value(),
Some(WindowsSandboxModeToml::Elevated)
);
assert!(
requirements
.windows_sandbox_mode
.can_set(&Some(WindowsSandboxModeToml::Elevated))
.is_ok()
);
assert!(
requirements
.windows_sandbox_mode
.can_set(&Some(WindowsSandboxModeToml::Unelevated))
.is_err()
);
assert!(requirements.windows_sandbox_mode.can_set(&None).is_err());
Ok(())
}
#[test]
fn empty_allowed_windows_sandbox_implementations_is_rejected() -> Result<()> {
let toml_str = r#"
[windows]
allowed_sandbox_implementations = []
"#;
let config: ConfigRequirementsToml = from_str(toml_str)?;
assert_eq!(
ConfigRequirements::try_from(with_unknown_source(config)),
Err(ConstraintError::EmptyField {
field_name: "windows.allowed_sandbox_implementations".to_string(),
})
);
Ok(())
}
#[test]
fn allowed_windows_sandbox_implementations_prefer_elevated_fallback() -> Result<()> {
let toml_str = r#"
[windows]
allowed_sandbox_implementations = ["unelevated", "elevated"]
"#;
let config: ConfigRequirementsToml = from_str(toml_str)?;
let requirements: ConfigRequirements = with_unknown_source(config).try_into()?;
assert_eq!(
requirements.windows_sandbox_mode.value(),
Some(WindowsSandboxModeToml::Elevated)
);
Ok(())
}
#[test]
fn deserialize_legacy_allowed_approvals_reviewer() -> Result<()> {
let toml_str = r#"
+12
View File
@@ -87,6 +87,10 @@ const fn default_hide_agent_reasoning() -> Option<bool> {
Some(false)
}
const fn default_true() -> bool {
true
}
/// Backward-compatible shape for ChatGPT workspace login restrictions in config.toml.
#[derive(Serialize, Debug, Clone, PartialEq, JsonSchema)]
#[serde(untagged)]
@@ -617,6 +621,14 @@ pub struct ToolsToml {
deserialize_with = "deserialize_optional_web_search_tool_config"
)]
pub web_search: Option<WebSearchToolConfig>,
pub experimental_request_user_input: Option<ExperimentalRequestUserInput>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct ExperimentalRequestUserInput {
#[serde(default = "default_true")]
pub enabled: bool,
}
#[derive(Deserialize)]
+23 -2
View File
@@ -4,6 +4,7 @@
use crate::ConfigLayerEntry;
use crate::ConfigLayerStack;
use crate::ConfigLayerStackOrdering;
use crate::format_config_layer_source;
use codex_app_server_protocol::ConfigLayerSource;
use codex_utils_absolute_path::AbsolutePathBufGuard;
use serde::de::DeserializeOwned;
@@ -89,7 +90,6 @@ impl std::error::Error for ConfigLoadError {
#[derive(Clone, Copy)]
pub(crate) enum ConfigDiagnosticSource<'a> {
Path(&'a Path),
#[cfg(any(target_os = "macos", test))]
DisplayName(&'a str),
}
@@ -97,7 +97,6 @@ impl ConfigDiagnosticSource<'_> {
pub(crate) fn to_path_buf(self) -> PathBuf {
match self {
ConfigDiagnosticSource::Path(path) => path.to_path_buf(),
#[cfg(any(target_os = "macos", test))]
ConfigDiagnosticSource::DisplayName(name) => PathBuf::from(name),
}
}
@@ -201,6 +200,27 @@ where
I: IntoIterator<Item = &'a ConfigLayerEntry>,
{
for layer in layers {
if let Some(contents) = layer.raw_toml() {
let source_name = format_config_layer_source(&layer.name, config_toml_file);
let Some(base_dir) = layer.raw_toml_base_dir() else {
tracing::debug!(
"Skipping raw TOML diagnostics for {source_name} because it has no base directory"
);
continue;
};
// Match the base directory used when the raw non-file layer was
// parsed into the runtime layer so diagnostics resolve relative
// path fields with the same semantics.
let _absolute_path_base = AbsolutePathBufGuard::new(base_dir.as_path());
if let Some(error) = config_error_from_typed_toml_for_source::<T>(
ConfigDiagnosticSource::DisplayName(&source_name),
contents,
) {
return Some(error);
}
continue;
}
let Some(path) = config_path_for_layer(layer, config_toml_file) else {
continue;
};
@@ -235,6 +255,7 @@ fn config_path_for_layer(layer: &ConfigLayerEntry, config_toml_file: &str) -> Op
}
ConfigLayerSource::LegacyManagedConfigTomlFromFile { file } => Some(file.to_path_buf()),
ConfigLayerSource::Mdm { .. }
| ConfigLayerSource::EnterpriseManaged { .. }
| ConfigLayerSource::SessionFlags
| ConfigLayerSource::LegacyManagedConfigTomlFromMdm => None,
}
+11
View File
@@ -1,4 +1,6 @@
mod cloud_config_layers;
mod cloud_requirements;
mod config_layer_source;
mod config_requirements;
pub mod config_toml;
mod constraint;
@@ -18,6 +20,7 @@ mod plugin_edit;
pub mod profile_toml;
mod project_root_markers;
mod requirements_exec_policy;
mod requirements_layers;
pub mod schema;
mod skills_config;
mod state;
@@ -28,6 +31,10 @@ pub mod types;
pub const CONFIG_TOML_FILE: &str = "config.toml";
pub use cloud_config_layers::CloudConfigFragment;
pub use cloud_config_layers::CloudConfigFragmentSource;
pub use cloud_config_layers::CloudConfigLayerError;
pub use cloud_config_layers::cloud_config_layers_from_fragments;
pub use cloud_requirements::CloudRequirementsLoadError;
pub use cloud_requirements::CloudRequirementsLoadErrorCode;
pub use cloud_requirements::CloudRequirementsLoader;
@@ -35,6 +42,7 @@ pub use codex_app_server_protocol::ConfigLayerSource;
pub use codex_protocol::config_types::ProfileV2Name;
pub use codex_protocol::config_types::ProfileV2NameParseError;
pub use codex_utils_absolute_path::AbsolutePathBuf;
pub use config_layer_source::format_config_layer_source;
pub use config_requirements::AppRequirementToml;
pub use config_requirements::AppToolRequirementToml;
pub use config_requirements::AppToolsRequirementsToml;
@@ -62,6 +70,7 @@ pub use config_requirements::ResidencyRequirement;
pub use config_requirements::SandboxModeRequirement;
pub use config_requirements::Sourced;
pub use config_requirements::WebSearchModeRequirement;
pub use config_requirements::WindowsRequirementsToml;
pub use config_requirements::sandbox_mode_requirement_for_permission_profile;
pub use constraint::Constrained;
pub use constraint::ConstraintError;
@@ -116,6 +125,8 @@ pub use requirements_exec_policy::RequirementsExecPolicyParseError;
pub use requirements_exec_policy::RequirementsExecPolicyPatternTokenToml;
pub use requirements_exec_policy::RequirementsExecPolicyPrefixRuleToml;
pub use requirements_exec_policy::RequirementsExecPolicyToml;
pub use requirements_layers::RequirementsLayerEntry;
pub use requirements_layers::compose_requirements;
pub use skills_config::BundledSkillsConfig;
pub use skills_config::SkillConfig;
pub use skills_config::SkillsConfig;
+8 -3
View File
@@ -366,13 +366,18 @@ pub async fn load_config_layers_state(
// paths, starting with `./`, but a path starting with `~/` _is_ a
// supported use case. Because resolve_relative_paths_in_config_toml()
// relies on AbsolutePathBufGuard to resolve `~/`, we must supply a
// value for base_dir, so codex_home is as good a value as any.
let managed_config =
resolve_relative_paths_in_config_toml(config.managed_config, codex_home)?;
// value for base_dir. Preserve that same base on the layer so later
// raw-TOML diagnostics parse with the same path semantics.
let raw_toml_base_dir = AbsolutePathBuf::from_absolute_path(codex_home)?;
let managed_config = resolve_relative_paths_in_config_toml(
config.managed_config,
raw_toml_base_dir.as_path(),
)?;
layers.push(ConfigLayerEntry::new_with_raw_toml(
ConfigLayerSource::LegacyManagedConfigTomlFromMdm,
managed_config,
config.raw_toml,
raw_toml_base_dir,
));
}
@@ -0,0 +1,237 @@
//! Hook events are append-only across requirements layers. The managed hook
//! directory is different: only one directory is usable on a given platform, so
//! conflicting values for the active platform fail closed. The inactive platform
//! field is first-filled to allow the same layer stack to carry OS-specific
//! directories.
use crate::HookEventsToml;
use crate::ManagedHooksRequirementsToml;
use crate::RequirementSource;
use crate::Sourced;
use std::collections::BTreeMap;
use std::path::PathBuf;
use super::stack::composition_conflict;
use super::stack::merge_output_source;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub(super) enum HookDirectoryField {
#[default]
ManagedDir,
WindowsManagedDir,
}
impl HookDirectoryField {
pub(super) fn current_platform() -> Self {
if cfg!(windows) {
Self::WindowsManagedDir
} else {
Self::ManagedDir
}
}
fn field_name(self) -> &'static str {
match self {
Self::ManagedDir => "hooks.managed_dir",
Self::WindowsManagedDir => "hooks.windows_managed_dir",
}
}
fn inactive(self) -> Self {
match self {
Self::ManagedDir => Self::WindowsManagedDir,
Self::WindowsManagedDir => Self::ManagedDir,
}
}
}
pub(super) struct HookMergeState {
directory_field: HookDirectoryField,
dir_sources: BTreeMap<HookDirectoryField, RequirementSource>,
}
impl HookMergeState {
pub(super) fn new(directory_field: HookDirectoryField) -> Self {
Self {
directory_field,
dir_sources: BTreeMap::new(),
}
}
pub(super) fn merge(
&mut self,
target: &mut Option<Sourced<ManagedHooksRequirementsToml>>,
incoming: Option<ManagedHooksRequirementsToml>,
source: &RequirementSource,
) -> Result<(), super::stack::RequirementsCompositionError> {
let Some(mut incoming) = incoming.filter(|value| !value.is_empty()) else {
return Ok(());
};
let Some(existing) = target.as_mut() else {
self.track_singleton_source(
HookDirectoryField::ManagedDir,
&incoming.managed_dir,
source,
);
self.track_singleton_source(
HookDirectoryField::WindowsManagedDir,
&incoming.windows_managed_dir,
source,
);
*target = Some(Sourced::new(incoming, source.clone()));
return Ok(());
};
let active_field = self.directory_field;
let inactive_field = active_field.inactive();
let incoming_active_dir = take_hook_dir(&mut incoming, active_field);
let incoming_inactive_dir = take_hook_dir(&mut incoming, inactive_field);
let mut changed = false;
changed |= self.merge_active_singleton(
active_field,
hook_dir_mut(&mut existing.value, active_field),
incoming_active_dir,
source,
)?;
changed |= self.fill_singleton(
inactive_field,
hook_dir_mut(&mut existing.value, inactive_field),
incoming_inactive_dir,
source,
);
changed |= append_hook_events(&mut existing.value.hooks, incoming.hooks);
if changed {
merge_output_source(&mut existing.source, source);
}
Ok(())
}
fn track_singleton_source(
&mut self,
field: HookDirectoryField,
value: &Option<PathBuf>,
source: &RequirementSource,
) {
if value.is_some() {
self.dir_sources
.entry(field)
.or_insert_with(|| source.clone());
}
}
fn merge_active_singleton(
&mut self,
field: HookDirectoryField,
existing: &mut Option<PathBuf>,
incoming: Option<PathBuf>,
incoming_source: &RequirementSource,
) -> Result<bool, super::stack::RequirementsCompositionError> {
let Some(incoming) = incoming else {
return Ok(false);
};
match existing {
Some(existing_value) if existing_value != &incoming => {
let existing_source = self
.dir_sources
.get(&field)
.cloned()
.unwrap_or_else(|| incoming_source.clone());
Err(composition_conflict(
field.field_name().to_string(),
existing_source,
incoming_source.clone(),
format!(
"`{}` conflicts with `{}`",
existing_value.display(),
incoming.display()
),
))
}
Some(_) => Ok(false),
None => {
*existing = Some(incoming);
self.dir_sources
.entry(field)
.or_insert_with(|| incoming_source.clone());
Ok(true)
}
}
}
fn fill_singleton(
&mut self,
field: HookDirectoryField,
existing: &mut Option<PathBuf>,
incoming: Option<PathBuf>,
incoming_source: &RequirementSource,
) -> bool {
if existing.is_none()
&& let Some(incoming) = incoming
{
*existing = Some(incoming);
self.dir_sources
.entry(field)
.or_insert_with(|| incoming_source.clone());
true
} else {
false
}
}
}
fn take_hook_dir(
hooks: &mut ManagedHooksRequirementsToml,
field: HookDirectoryField,
) -> Option<PathBuf> {
match field {
HookDirectoryField::ManagedDir => hooks.managed_dir.take(),
HookDirectoryField::WindowsManagedDir => hooks.windows_managed_dir.take(),
}
}
fn hook_dir_mut(
hooks: &mut ManagedHooksRequirementsToml,
field: HookDirectoryField,
) -> &mut Option<PathBuf> {
match field {
HookDirectoryField::ManagedDir => &mut hooks.managed_dir,
HookDirectoryField::WindowsManagedDir => &mut hooks.windows_managed_dir,
}
}
fn append_hook_events(existing: &mut HookEventsToml, incoming: HookEventsToml) -> bool {
// Destructure without `..` so new hook events cannot be introduced without
// deciding whether requirements layer merging should append them.
let HookEventsToml {
pre_tool_use,
permission_request,
post_tool_use,
pre_compact,
post_compact,
session_start,
user_prompt_submit,
subagent_start,
subagent_stop,
stop,
} = incoming;
let mut changed = false;
changed |= append_vec(&mut existing.pre_tool_use, pre_tool_use);
changed |= append_vec(&mut existing.permission_request, permission_request);
changed |= append_vec(&mut existing.post_tool_use, post_tool_use);
changed |= append_vec(&mut existing.pre_compact, pre_compact);
changed |= append_vec(&mut existing.post_compact, post_compact);
changed |= append_vec(&mut existing.session_start, session_start);
changed |= append_vec(&mut existing.user_prompt_submit, user_prompt_submit);
changed |= append_vec(&mut existing.subagent_start, subagent_start);
changed |= append_vec(&mut existing.subagent_stop, subagent_stop);
changed |= append_vec(&mut existing.stop, stop);
changed
}
fn append_vec<T>(existing: &mut Vec<T>, mut incoming: Vec<T>) -> bool {
let changed = !incoming.is_empty();
existing.append(&mut incoming);
changed
}
@@ -0,0 +1,191 @@
use crate::ConfigRequirementsToml;
use crate::ManagedHooksRequirementsToml;
use crate::RequirementSource;
use crate::RequirementsExecPolicyToml;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_absolute_path::AbsolutePathBufGuard;
use toml::Value as TomlValue;
use super::stack::RequirementsCompositionError;
#[derive(Clone, Debug)]
pub struct RequirementsLayerEntry {
pub(super) source: RequirementSource,
toml: RequirementsLayerToml,
base_dir: Option<AbsolutePathBuf>,
}
impl RequirementsLayerEntry {
pub fn from_toml(source: RequirementSource, contents: impl Into<String>) -> Self {
Self {
source,
toml: RequirementsLayerToml::String(contents.into()),
base_dir: None,
}
}
pub fn from_toml_value(source: RequirementSource, value: TomlValue) -> Self {
Self {
source,
toml: RequirementsLayerToml::Value(value),
base_dir: None,
}
}
pub fn with_base_dir(mut self, base_dir: AbsolutePathBuf) -> Self {
self.base_dir = Some(base_dir);
self
}
}
#[derive(Clone, Debug)]
enum RequirementsLayerToml {
String(String),
Value(TomlValue),
}
#[derive(Clone, Debug)]
pub(super) struct ComposableRequirementsLayer {
pub(super) source: RequirementSource,
pub(super) regular_toml: TomlValue,
pub(super) domain_fields: DomainMergedRequirementsFields,
}
impl ComposableRequirementsLayer {
pub(super) fn from_entry(
layer: RequirementsLayerEntry,
hostname: Option<&str>,
) -> Result<Self, RequirementsCompositionError> {
let RequirementsLayerEntry {
source,
toml,
base_dir,
} = layer;
let (mut regular_toml, mut requirements) = {
let _guard = base_dir
.as_ref()
.map(|base_dir| AbsolutePathBufGuard::new(base_dir.as_path()));
let regular_toml = parse_layer_toml(&toml, &source)?;
let requirements = parse_layer_requirements(&toml, &source)?;
(regular_toml, requirements)
};
requirements.apply_remote_sandbox_config(hostname);
materialize_remote_sandbox_config(&mut regular_toml, &requirements)?;
strip_special_fields(&mut regular_toml);
Ok(Self {
source,
regular_toml,
domain_fields: DomainMergedRequirementsFields {
rules: requirements.rules,
hooks: requirements.hooks,
permissions: requirements.permissions,
},
})
}
}
#[derive(Clone, Debug)]
pub(super) struct DomainMergedRequirementsFields {
pub(super) rules: Option<RequirementsExecPolicyToml>,
pub(super) hooks: Option<ManagedHooksRequirementsToml>,
pub(super) permissions: Option<crate::config_requirements::PermissionsRequirementsToml>,
}
fn parse_layer_toml(
toml: &RequirementsLayerToml,
source: &RequirementSource,
) -> Result<TomlValue, RequirementsCompositionError> {
match toml {
RequirementsLayerToml::String(contents) => {
toml::from_str(contents).map_err(|err: toml::de::Error| {
RequirementsCompositionError::Parse {
layer_source: source.clone(),
message: err.to_string(),
}
})
}
RequirementsLayerToml::Value(value) => Ok(value.clone()),
}
}
fn parse_layer_requirements(
toml: &RequirementsLayerToml,
source: &RequirementSource,
) -> Result<ConfigRequirementsToml, RequirementsCompositionError> {
match toml {
RequirementsLayerToml::String(contents) => {
toml::from_str(contents).map_err(|err: toml::de::Error| {
RequirementsCompositionError::Parse {
layer_source: source.clone(),
message: err.to_string(),
}
})
}
RequirementsLayerToml::Value(value) => {
value.clone().try_into().map_err(|err: toml::de::Error| {
RequirementsCompositionError::Parse {
layer_source: source.clone(),
message: err.to_string(),
}
})
}
}
}
fn materialize_remote_sandbox_config(
layer_toml: &mut TomlValue,
requirements: &ConfigRequirementsToml,
) -> Result<(), RequirementsCompositionError> {
remove_top_level_field(layer_toml, "remote_sandbox_config");
let Some(allowed_sandbox_modes) = requirements.allowed_sandbox_modes.as_ref() else {
return Ok(());
};
let Some(table) = layer_toml.as_table_mut() else {
return Ok(());
};
table.insert(
"allowed_sandbox_modes".to_string(),
toml_value_from_serializable(allowed_sandbox_modes)?,
);
Ok(())
}
fn toml_value_from_serializable<T: serde::Serialize>(
value: T,
) -> Result<TomlValue, RequirementsCompositionError> {
TomlValue::try_from(value).map_err(|err| RequirementsCompositionError::ComposedParse {
message: err.to_string(),
})
}
fn strip_special_fields(layer_toml: &mut TomlValue) {
remove_top_level_field(layer_toml, "rules");
remove_top_level_field(layer_toml, "hooks");
remove_nested_field_and_prune_empty(layer_toml, &["permissions", "filesystem", "deny_read"]);
}
fn remove_top_level_field(value: &mut TomlValue, key: &str) -> Option<TomlValue> {
value.as_table_mut()?.remove(key)
}
fn remove_nested_field_and_prune_empty(value: &mut TomlValue, path: &[&str]) -> Option<TomlValue> {
let (key, remaining) = path.split_first()?;
let table = value.as_table_mut()?;
if remaining.is_empty() {
return table.remove(*key);
}
let removed = table
.get_mut(*key)
.and_then(|child| remove_nested_field_and_prune_empty(child, remaining));
if table
.get(*key)
.and_then(TomlValue::as_table)
.is_some_and(toml::map::Map::is_empty)
{
table.remove(*key);
}
removed
}
@@ -0,0 +1,8 @@
mod hooks;
mod layer;
mod permissions;
mod rules;
mod stack;
pub use layer::RequirementsLayerEntry;
pub use stack::compose_requirements;
@@ -0,0 +1,82 @@
//! `permissions.filesystem.deny_read` is intentionally additive across
//! requirements layers. Other `[permissions]` content stays in the regular TOML
//! merge path so permission profile tables follow config-style precedence.
use crate::FilesystemDenyReadPattern;
use crate::RequirementSource;
use crate::Sourced;
use crate::config_requirements::FilesystemRequirementsToml;
use crate::config_requirements::PermissionsRequirementsToml;
use super::stack::merge_output_source;
#[derive(Default)]
pub(super) struct DenyReadMergeState {
deny_read: Vec<FilesystemDenyReadPattern>,
source: Option<RequirementSource>,
}
impl DenyReadMergeState {
pub(super) fn merge(
&mut self,
incoming: Option<PermissionsRequirementsToml>,
source: &RequirementSource,
) {
let Some(incoming_deny_read) = incoming
.and_then(|permissions| permissions.filesystem)
.and_then(|filesystem| filesystem.deny_read)
.filter(|deny_read| !deny_read.is_empty())
else {
return;
};
for pattern in incoming_deny_read {
if !self.deny_read.contains(&pattern) {
self.deny_read.push(pattern);
self.merge_source(source);
}
}
}
pub(super) fn apply_to(self, target: &mut Option<Sourced<PermissionsRequirementsToml>>) {
if self.deny_read.is_empty() {
return;
}
let source = self.source.unwrap_or(RequirementSource::Unknown);
let Some(existing) = target.as_mut() else {
*target = Some(Sourced::new(
PermissionsRequirementsToml {
filesystem: Some(FilesystemRequirementsToml {
deny_read: Some(self.deny_read),
}),
profiles: Default::default(),
},
source,
));
return;
};
let filesystem = existing
.value
.filesystem
.get_or_insert_with(Default::default);
let deny_read = filesystem.deny_read.get_or_insert_with(Vec::new);
for pattern in self.deny_read {
if !deny_read.contains(&pattern) {
deny_read.push(pattern);
}
}
if existing.source != source {
existing.source = RequirementSource::composite([existing.source.clone(), source]);
}
}
fn merge_source(&mut self, source: &RequirementSource) {
let Some(existing) = self.source.as_mut() else {
self.source = Some(source.clone());
return;
};
merge_output_source(existing, source);
}
}
@@ -0,0 +1,26 @@
//! Requirements rules are additive across layers. Higher-priority rules are
//! appended first so the final rule order keeps priority visible.
use crate::RequirementSource;
use crate::RequirementsExecPolicyToml;
use crate::Sourced;
use super::stack::merge_output_source;
pub(super) fn merge(
target: &mut Option<Sourced<RequirementsExecPolicyToml>>,
incoming: Option<RequirementsExecPolicyToml>,
source: &RequirementSource,
) {
let Some(incoming) = incoming else {
return;
};
let Some(existing) = target.as_mut() else {
*target = Some(Sourced::new(incoming, source.clone()));
return;
};
let RequirementsExecPolicyToml { prefix_rules } = incoming;
existing.value.prefix_rules.extend(prefix_rules);
merge_output_source(&mut existing.source, source);
}
@@ -0,0 +1,286 @@
//! Requirements layers are composed in the same order as config layers: lowest
//! precedence first, highest precedence last. Most fields use the same
//! TOML-level merge policy as config: lower-priority layers provide defaults,
//! and higher-priority layers override scalar/list values while recursively
//! extending tables.
//!
//! A few fields carry domain-specific meaning that raw TOML replacement would
//! break:
//! - `remote_sandbox_config` is evaluated within each layer before merging.
//! - `rules.prefix_rules` append high-priority rules first.
//! - `hooks` append high-priority event groups first while failing closed on
//! active managed-dir conflicts.
//! - `permissions.filesystem.deny_read` is a high-priority-first union across
//! layers.
use crate::ConfigRequirementsToml;
use crate::ConfigRequirementsWithSources;
use crate::RequirementSource;
use crate::Sourced;
use crate::merge::merge_toml_values;
use std::io;
use thiserror::Error;
use toml::Value as TomlValue;
use super::hooks::HookDirectoryField;
use super::hooks::HookMergeState;
use super::layer::ComposableRequirementsLayer;
use super::layer::RequirementsLayerEntry;
use super::permissions::DenyReadMergeState;
#[derive(Debug, Error, PartialEq, Eq)]
pub enum RequirementsCompositionError {
#[error("failed to parse requirements layer {layer_source}: {message}")]
Parse {
layer_source: RequirementSource,
message: String,
},
#[error("failed to parse merged requirements: {message}")]
ComposedParse { message: String },
#[error(
"failed to compose requirements field `{field}` between {existing_source} and {incoming_source}: {message}"
)]
Conflict {
field: String,
existing_source: RequirementSource,
incoming_source: RequirementSource,
message: String,
},
}
impl From<RequirementsCompositionError> for io::Error {
fn from(error: RequirementsCompositionError) -> Self {
io::Error::new(io::ErrorKind::InvalidData, error)
}
}
pub fn compose_requirements(
layers: impl IntoIterator<Item = RequirementsLayerEntry>,
) -> Result<Option<ConfigRequirementsWithSources>, RequirementsCompositionError> {
let hostname = crate::host_name();
compose_requirements_for_hostname(layers, hostname.as_deref())
}
pub(super) fn compose_requirements_for_hostname(
layers: impl IntoIterator<Item = RequirementsLayerEntry>,
hostname: Option<&str>,
) -> Result<Option<ConfigRequirementsWithSources>, RequirementsCompositionError> {
compose_requirements_for_hostname_and_hook_directory(
layers,
hostname,
HookDirectoryField::current_platform(),
)
}
pub(super) fn compose_requirements_for_hostname_and_hook_directory(
layers: impl IntoIterator<Item = RequirementsLayerEntry>,
hostname: Option<&str>,
hook_directory_field: HookDirectoryField,
) -> Result<Option<ConfigRequirementsWithSources>, RequirementsCompositionError> {
let mut stack = RequirementsLayerStack::new(hook_directory_field);
for layer in layers {
stack.add_layer(layer, hostname)?;
}
stack.compose()
}
struct RequirementsLayerStack {
layers: Vec<ComposableRequirementsLayer>,
hook_directory_field: HookDirectoryField,
}
impl RequirementsLayerStack {
fn new(hook_directory_field: HookDirectoryField) -> Self {
Self {
layers: Vec::new(),
hook_directory_field,
}
}
fn add_layer(
&mut self,
layer: RequirementsLayerEntry,
hostname: Option<&str>,
) -> Result<(), RequirementsCompositionError> {
self.layers
.push(ComposableRequirementsLayer::from_entry(layer, hostname)?);
Ok(())
}
fn compose(
self,
) -> Result<Option<ConfigRequirementsWithSources>, RequirementsCompositionError> {
let Self {
layers,
hook_directory_field,
} = self;
let mut merged_toml = TomlValue::Table(toml::map::Map::new());
for layer in &layers {
merge_toml_values(&mut merged_toml, &layer.regular_toml);
}
let requirements: ConfigRequirementsToml =
merged_toml.try_into().map_err(|err: toml::de::Error| {
RequirementsCompositionError::ComposedParse {
message: err.to_string(),
}
})?;
let mut output = ConfigRequirementsWithSources::default();
populate_merged_regular_fields_with_sources(&mut output, requirements, &layers);
let mut rules = None;
let mut hooks = HookMergeState::new(hook_directory_field);
let mut hooks_output = None;
let mut deny_read = DenyReadMergeState::default();
// Regular TOML fields are folded low-to-high like config. These custom
// fields append or union values, so process them high-to-low to keep
// priority order visible in the output.
for layer in layers.iter().rev() {
let domain_fields = &layer.domain_fields;
super::rules::merge(&mut rules, domain_fields.rules.clone(), &layer.source);
hooks.merge(
&mut hooks_output,
domain_fields.hooks.clone(),
&layer.source,
)?;
deny_read.merge(domain_fields.permissions.clone(), &layer.source);
}
output.rules = rules;
output.hooks = hooks_output;
deny_read.apply_to(&mut output.permissions);
let output_is_empty = output.clone().into_toml().is_empty();
Ok((!output_is_empty).then_some(output))
}
}
fn populate_merged_regular_fields_with_sources(
output: &mut ConfigRequirementsWithSources,
requirements: ConfigRequirementsToml,
layers: &[ComposableRequirementsLayer],
) {
macro_rules! set_sourced {
($field:ident, $keys:expr) => {
if let Some(value) = $field {
output.$field = Some(Sourced::new(
value,
source_for_top_level_keys(layers, $keys),
));
}
};
}
// Destructure without `..` so every new requirements field must choose
// whether it belongs in the regular TOML merge path or in a special merger.
let ConfigRequirementsToml {
allowed_approval_policies,
allowed_approvals_reviewers,
allowed_sandbox_modes,
allowed_permissions,
remote_sandbox_config: _,
allowed_web_search_modes,
allow_managed_hooks_only,
allow_appshots,
computer_use,
windows,
feature_requirements,
hooks: _,
mcp_servers,
plugins,
apps,
rules: _,
enforce_residency,
network,
permissions,
guardian_policy_config,
} = requirements;
set_sourced!(allowed_approval_policies, &["allowed_approval_policies"]);
set_sourced!(
allowed_approvals_reviewers,
&["allowed_approvals_reviewers"]
);
set_sourced!(allowed_sandbox_modes, &["allowed_sandbox_modes"]);
set_sourced!(allowed_permissions, &["allowed_permissions"]);
set_sourced!(allowed_web_search_modes, &["allowed_web_search_modes"]);
set_sourced!(allow_managed_hooks_only, &["allow_managed_hooks_only"]);
set_sourced!(allow_appshots, &["allow_appshots"]);
set_sourced!(computer_use, &["computer_use"]);
set_sourced!(windows, &["windows"]);
set_sourced!(feature_requirements, &["features", "feature_requirements"]);
set_sourced!(mcp_servers, &["mcp_servers"]);
set_sourced!(plugins, &["plugins"]);
set_sourced!(apps, &["apps"]);
set_sourced!(enforce_residency, &["enforce_residency"]);
set_sourced!(network, &["experimental_network"]);
set_sourced!(permissions, &["permissions"]);
if let Some(guardian_policy_config) =
guardian_policy_config.filter(|value| !value.trim().is_empty())
{
output.guardian_policy_config = Some(Sourced::new(
guardian_policy_config,
source_for_top_level_keys(layers, &["guardian_policy_config"]),
));
}
}
fn source_for_top_level_keys(
layers: &[ComposableRequirementsLayer],
keys: &[&str],
) -> RequirementSource {
let matching_layers = layers
.iter()
.filter_map(|layer| {
top_level_value_for_keys(&layer.regular_toml, keys).map(|value| (&layer.source, value))
})
.collect::<Vec<_>>();
let Some((winning_source, winning_value)) = matching_layers.last() else {
return RequirementSource::Unknown;
};
let winning_source = (*winning_source).clone();
if !winning_value.is_table() {
return winning_source;
}
let table_sources = matching_layers
.into_iter()
.rev()
.filter_map(|(source, value)| value.is_table().then_some(source.clone()))
.collect::<Vec<_>>();
if table_sources.len() > 1 {
RequirementSource::composite(table_sources)
} else {
winning_source
}
}
fn top_level_value_for_keys<'a>(value: &'a TomlValue, keys: &[&str]) -> Option<&'a TomlValue> {
let table = value.as_table()?;
keys.iter().find_map(|key| table.get(*key))
}
pub(super) fn merge_output_source(existing: &mut RequirementSource, incoming: &RequirementSource) {
if existing != incoming {
*existing = RequirementSource::composite([existing.clone(), incoming.clone()]);
}
}
pub(super) fn composition_conflict(
field: String,
existing_source: RequirementSource,
incoming_source: RequirementSource,
message: impl Into<String>,
) -> RequirementsCompositionError {
RequirementsCompositionError::Conflict {
field,
existing_source,
incoming_source,
message: message.into(),
}
}
#[cfg(test)]
#[path = "stack_tests.rs"]
mod tests;
@@ -0,0 +1,922 @@
use super::super::RequirementsLayerEntry;
use super::super::hooks::HookDirectoryField;
use super::RequirementsCompositionError;
use super::compose_requirements_for_hostname;
use super::compose_requirements_for_hostname_and_hook_directory;
use crate::ConfigRequirementsToml;
use crate::ConfigRequirementsWithSources;
use crate::RequirementSource;
use crate::Sourced;
use codex_protocol::protocol::AskForApproval;
use codex_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
fn layer(id: &str, name: &str, contents: &str) -> RequirementsLayerEntry {
RequirementsLayerEntry::from_toml(
RequirementSource::EnterpriseManaged {
id: id.to_string(),
name: name.to_string(),
},
contents,
)
}
fn compose(
layers: Vec<RequirementsLayerEntry>,
) -> Result<Option<ConfigRequirementsToml>, RequirementsCompositionError> {
Ok(
compose_requirements_for_hostname(layers, /*hostname*/ None)?
.map(ConfigRequirementsWithSources::into_toml),
)
}
fn compose_with_hook_directory_field(
layers: Vec<RequirementsLayerEntry>,
hook_directory_field: HookDirectoryField,
) -> Result<Option<ConfigRequirementsToml>, RequirementsCompositionError> {
Ok(compose_requirements_for_hostname_and_hook_directory(
layers,
/*hostname*/ None,
hook_directory_field,
)?
.map(ConfigRequirementsWithSources::into_toml))
}
fn expected_requirements(contents: impl AsRef<str>) -> ConfigRequirementsToml {
toml::from_str(contents.as_ref()).expect("parse expected requirements TOML")
}
#[test]
fn empty_layers_compose_to_none() {
let composed = compose(Vec::new()).expect("compose empty layers");
assert_eq!(composed, None);
}
#[test]
fn top_level_values_use_toml_priority() {
let composed = compose(vec![
layer(
"req_low",
"Low",
r#"
allowed_approval_policies = ["on-request"]
allowed_sandbox_modes = ["workspace-write"]
"#,
),
layer(
"req_high",
"High",
r#"
allowed_approval_policies = ["never"]
allowed_sandbox_modes = ["read-only"]
"#,
),
])
.expect("compose requirements")
.expect("requirements present");
assert_eq!(
composed,
expected_requirements(
r#"
allowed_approval_policies = ["never"]
allowed_sandbox_modes = ["read-only"]
"#
)
);
}
#[test]
fn composition_strategy_applies_to_non_cloud_layers() {
let mdm_source = RequirementSource::MdmManagedPreferences {
domain: "com.openai.codex".to_string(),
key: "requirements_toml_base64".to_string(),
};
let system_file = if cfg!(windows) {
"C:\\requirements.toml"
} else {
"/etc/codex/requirements.toml"
};
let system_source = RequirementSource::SystemRequirementsToml {
file: AbsolutePathBuf::from_absolute_path(system_file).expect("absolute path"),
};
let high_path = if cfg!(windows) {
"C:\\secret"
} else {
"/secret"
};
let low_path = if cfg!(windows) {
"C:\\other-secret"
} else {
"/other-secret"
};
let composed = compose_requirements_for_hostname(
vec![
RequirementsLayerEntry::from_toml(
system_source,
format!(
r#"
allowed_approval_policies = ["on-request"]
[features]
shared = false
system = true
[[rules.prefix_rules]]
pattern = [{{ token = "npm" }}]
decision = "prompt"
[permissions.filesystem]
deny_read = [{low_path:?}]
"#
),
),
RequirementsLayerEntry::from_toml(
mdm_source.clone(),
format!(
r#"
allowed_approval_policies = ["never"]
[features]
shared = true
[[rules.prefix_rules]]
pattern = [{{ token = "git" }}]
decision = "forbidden"
[permissions.filesystem]
deny_read = [{high_path:?}]
"#
),
),
],
/*hostname*/ None,
)
.expect("compose requirements")
.expect("requirements present");
assert_eq!(
composed.clone().into_toml(),
expected_requirements(format!(
r#"
allowed_approval_policies = ["never"]
[features]
shared = true
system = true
[[rules.prefix_rules]]
pattern = [{{ token = "git" }}]
decision = "forbidden"
[[rules.prefix_rules]]
pattern = [{{ token = "npm" }}]
decision = "prompt"
[permissions.filesystem]
deny_read = [{high_path:?}, {low_path:?}]
"#
))
);
assert_eq!(
composed.allowed_approval_policies,
Some(Sourced::new(vec![AskForApproval::Never], mdm_source))
);
}
#[test]
fn single_regular_layer_keeps_enterprise_managed_source() {
let composed = compose_requirements_for_hostname(
vec![layer(
"req_1",
"Security baseline",
r#"
allow_managed_hooks_only = true
"#,
)],
/*hostname*/ None,
)
.expect("compose requirements")
.expect("requirements present");
assert_eq!(
composed.allow_managed_hooks_only,
Some(Sourced::new(
/*value*/ true,
RequirementSource::EnterpriseManaged {
id: "req_1".to_string(),
name: "Security baseline".to_string(),
},
))
);
}
#[test]
fn regular_toml_merge_recurses_into_tables() {
let composed = compose(vec![
layer(
"req_low",
"Low",
r#"
[features]
beta = false
shared = false
[apps.connector_1]
enabled = false
[apps.connector_1.tools.search]
approval_mode = "prompt"
[apps.connector_1.tools.list]
approval_mode = "prompt"
"#,
),
layer(
"req_high",
"High",
r#"
[features]
alpha = true
shared = true
[apps.connector_1]
enabled = true
[apps.connector_1.tools.search]
approval_mode = "approve"
"#,
),
])
.expect("compose requirements")
.expect("requirements present");
assert_eq!(
composed,
expected_requirements(
r#"
[features]
alpha = true
beta = false
shared = true
[apps.connector_1]
enabled = true
[apps.connector_1.tools.list]
approval_mode = "prompt"
[apps.connector_1.tools.search]
approval_mode = "approve"
"#
)
);
}
#[test]
fn merged_table_source_is_composite_in_priority_order() {
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#"
[features]
beta = true
"#,
),
RequirementsLayerEntry::from_toml(
high_source.clone(),
r#"
[features]
alpha = true
"#,
),
],
/*hostname*/ None,
)
.expect("compose requirements")
.expect("requirements present");
assert_eq!(
composed.feature_requirements.expect("features"),
Sourced::new(
crate::FeatureRequirementsToml {
entries: BTreeMap::from([("alpha".to_string(), true), ("beta".to_string(), true),]),
},
RequirementSource::composite([high_source, low_source]),
)
);
}
#[test]
fn mcp_requirements_use_regular_toml_merge() {
let composed = compose(vec![
layer(
"req_low",
"Low",
r#"
[mcp_servers.shared.identity]
command = "low-mcp"
[mcp_servers.low.identity]
url = "https://low.example.com/mcp"
"#,
),
layer(
"req_high",
"High",
r#"
[mcp_servers.shared.identity]
command = "high-mcp"
"#,
),
])
.expect("compose requirements")
.expect("requirements present");
assert_eq!(
composed,
expected_requirements(
r#"
[mcp_servers.low.identity]
url = "https://low.example.com/mcp"
[mcp_servers.shared.identity]
command = "high-mcp"
"#
)
);
}
#[test]
fn network_maps_use_regular_toml_merge() {
let composed = compose(vec![
layer(
"req_low",
"Low",
r#"
[experimental_network.domains]
"example.com" = "deny"
"low.example.com" = "deny"
"internal.example.com" = "allow"
[experimental_network.unix_sockets]
"/tmp/shared.sock" = "deny"
"/tmp/low.sock" = "allow"
"/tmp/admin.sock" = "allow"
"#,
),
layer(
"req_high",
"High",
r#"
[experimental_network.domains]
"example.com" = "allow"
"high.example.com" = "allow"
"internal.example.com" = "deny"
[experimental_network.unix_sockets]
"/tmp/shared.sock" = "allow"
"/tmp/high.sock" = "allow"
"/tmp/admin.sock" = "deny"
"#,
),
])
.expect("compose requirements")
.expect("requirements present");
assert_eq!(
composed,
expected_requirements(
r#"
[experimental_network.domains]
"example.com" = "allow"
"high.example.com" = "allow"
"internal.example.com" = "deny"
"low.example.com" = "deny"
[experimental_network.unix_sockets]
"/tmp/admin.sock" = "deny"
"/tmp/high.sock" = "allow"
"/tmp/low.sock" = "allow"
"/tmp/shared.sock" = "allow"
"#
)
);
}
#[test]
fn windows_requirements_use_regular_toml_merge() {
let composed = compose(vec![
layer(
"req_low",
"Low",
r#"
[windows]
allowed_sandbox_implementations = ["unelevated"]
"#,
),
layer(
"req_high",
"High",
r#"
[windows]
allowed_sandbox_implementations = ["elevated"]
"#,
),
])
.expect("compose requirements")
.expect("requirements present");
assert_eq!(
composed,
expected_requirements(
r#"
[windows]
allowed_sandbox_implementations = ["elevated"]
"#
)
);
}
#[test]
fn remote_sandbox_config_is_applied_per_layer() {
let composed = compose_requirements_for_hostname(
vec![
layer(
"req_low",
"Low",
r#"
allowed_sandbox_modes = ["read-only"]
"#,
),
layer(
"req_high",
"High",
r#"
[[remote_sandbox_config]]
hostname_patterns = ["build-*.example.com"]
allowed_sandbox_modes = ["workspace-write"]
"#,
),
],
Some("BUILD-01.EXAMPLE.COM."),
)
.expect("compose requirements")
.expect("requirements present")
.into_toml();
assert_eq!(
composed,
expected_requirements(
r#"
allowed_sandbox_modes = ["workspace-write"]
"#
)
);
}
#[test]
fn unmatched_remote_sandbox_config_does_not_shadow_lower_layers() {
let composed = compose_requirements_for_hostname(
vec![
layer(
"req_low",
"Low",
r#"
allowed_sandbox_modes = ["read-only"]
"#,
),
layer(
"req_high",
"High",
r#"
[[remote_sandbox_config]]
hostname_patterns = ["mac-*.example.com"]
allowed_sandbox_modes = ["workspace-write"]
"#,
),
],
Some("linux-01.example.com"),
)
.expect("compose requirements")
.expect("requirements present")
.into_toml();
assert_eq!(
composed,
expected_requirements(
r#"
allowed_sandbox_modes = ["read-only"]
"#
)
);
}
#[test]
fn rules_are_appended_in_priority_order() {
let composed = compose(vec![
layer(
"req_low",
"Low",
r#"
[[rules.prefix_rules]]
pattern = [{ token = "npm" }]
decision = "prompt"
"#,
),
layer(
"req_high",
"High",
r#"
[[rules.prefix_rules]]
pattern = [{ token = "git" }]
decision = "forbidden"
"#,
),
])
.expect("compose requirements")
.expect("requirements present");
assert_eq!(
composed,
expected_requirements(
r#"
[[rules.prefix_rules]]
pattern = [{ token = "git" }]
decision = "forbidden"
[[rules.prefix_rules]]
pattern = [{ token = "npm" }]
decision = "prompt"
"#
)
);
}
#[test]
fn hooks_append_groups_and_reject_conflicting_managed_dirs() {
let composed = compose_with_hook_directory_field(
vec![
layer(
"req_low",
"Low",
r#"
[hooks]
managed_dir = "/managed/hooks"
[[hooks.PreToolUse]]
matcher = "Bash"
[[hooks.PreToolUse.hooks]]
type = "command"
command = "low"
"#,
),
layer(
"req_high",
"High",
r#"
[hooks]
managed_dir = "/managed/hooks"
[[hooks.PreToolUse]]
matcher = "Edit"
[[hooks.PreToolUse.hooks]]
type = "command"
command = "high"
"#,
),
],
HookDirectoryField::ManagedDir,
)
.expect("compose requirements")
.expect("requirements present");
assert_eq!(
composed,
expected_requirements(
r#"
[hooks]
managed_dir = "/managed/hooks"
[[hooks.PreToolUse]]
matcher = "Edit"
[[hooks.PreToolUse.hooks]]
type = "command"
command = "high"
[[hooks.PreToolUse]]
matcher = "Bash"
[[hooks.PreToolUse.hooks]]
type = "command"
command = "low"
"#
)
);
let err = compose_with_hook_directory_field(
vec![
layer(
"req_low",
"Low",
r#"
[hooks]
managed_dir = "/managed/low"
"#,
),
layer(
"req_high",
"High",
r#"
[hooks]
managed_dir = "/managed/high"
"#,
),
],
HookDirectoryField::ManagedDir,
)
.expect_err("conflicting managed dirs should fail closed");
assert!(err.to_string().contains("hooks.managed_dir"));
assert!(err.to_string().contains("High (req_high)"));
assert!(err.to_string().contains("Low (req_low)"));
}
#[test]
fn active_windows_managed_dir_conflicts_fail_closed() {
let err = compose_with_hook_directory_field(
vec![
layer(
"req_low",
"Low",
r#"
[hooks]
windows_managed_dir = 'C:\managed\low'
"#,
),
layer(
"req_high",
"High",
r#"
[hooks]
windows_managed_dir = 'C:\managed\high'
"#,
),
],
HookDirectoryField::WindowsManagedDir,
)
.expect_err("conflicting windows managed dirs should fail closed");
assert!(err.to_string().contains("hooks.windows_managed_dir"));
assert!(err.to_string().contains("High (req_high)"));
assert!(err.to_string().contains("Low (req_low)"));
}
#[test]
fn inactive_hook_dir_conflicts_do_not_fail_composition() {
let composed = compose_with_hook_directory_field(
vec![
layer(
"req_low",
"Low",
r#"
[hooks]
managed_dir = "/managed/hooks"
windows_managed_dir = 'C:\managed\low'
[[hooks.PreToolUse]]
matcher = "Bash"
[[hooks.PreToolUse.hooks]]
type = "command"
command = "low"
"#,
),
layer(
"req_high",
"High",
r#"
[hooks]
managed_dir = "/managed/hooks"
windows_managed_dir = 'C:\managed\high'
[[hooks.PreToolUse]]
matcher = "Edit"
[[hooks.PreToolUse.hooks]]
type = "command"
command = "high"
"#,
),
],
HookDirectoryField::ManagedDir,
)
.expect("inactive windows managed dir conflict should not fail")
.expect("requirements present");
assert_eq!(
composed,
expected_requirements(
r#"
[hooks]
managed_dir = "/managed/hooks"
windows_managed_dir = 'C:\managed\high'
[[hooks.PreToolUse]]
matcher = "Edit"
[[hooks.PreToolUse.hooks]]
type = "command"
command = "high"
[[hooks.PreToolUse]]
matcher = "Bash"
[[hooks.PreToolUse.hooks]]
type = "command"
command = "low"
"#
)
);
let composed = compose_with_hook_directory_field(
vec![
layer(
"req_low",
"Low",
r#"
[hooks]
managed_dir = "/managed/low"
windows_managed_dir = 'C:\managed\hooks'
[[hooks.PreToolUse]]
matcher = "Bash"
[[hooks.PreToolUse.hooks]]
type = "command"
command = "low"
"#,
),
layer(
"req_high",
"High",
r#"
[hooks]
managed_dir = "/managed/high"
windows_managed_dir = 'C:\managed\hooks'
[[hooks.PreToolUse]]
matcher = "Edit"
[[hooks.PreToolUse.hooks]]
type = "command"
command = "high"
"#,
),
],
HookDirectoryField::WindowsManagedDir,
)
.expect("inactive managed dir conflict should not fail")
.expect("requirements present");
assert_eq!(
composed,
expected_requirements(
r#"
[hooks]
managed_dir = "/managed/high"
windows_managed_dir = 'C:\managed\hooks'
[[hooks.PreToolUse]]
matcher = "Edit"
[[hooks.PreToolUse.hooks]]
type = "command"
command = "high"
[[hooks.PreToolUse]]
matcher = "Bash"
[[hooks.PreToolUse.hooks]]
type = "command"
command = "low"
"#
)
);
}
#[test]
fn permissions_deny_read_unions_while_profiles_use_regular_toml_merge() {
let high_path = if cfg!(windows) {
"C:\\secret"
} else {
"/secret"
};
let low_path = if cfg!(windows) {
"C:\\other-secret"
} else {
"/other-secret"
};
let composed = compose(vec![
layer(
"req_low",
"Low",
&format!(
r#"
[permissions.filesystem]
deny_read = [{high_path:?}, {low_path:?}]
[permissions.managed-standard]
description = "Low profile"
extends = ":workspace"
"#
),
),
layer(
"req_high",
"High",
&format!(
r#"
[permissions.filesystem]
deny_read = [{high_path:?}]
[permissions.managed-standard]
description = "High profile"
"#
),
),
])
.expect("compose requirements")
.expect("requirements present");
assert_eq!(
composed,
expected_requirements(format!(
r#"
[permissions.filesystem]
deny_read = [{high_path:?}, {low_path:?}]
[permissions.managed-standard]
description = "High profile"
extends = ":workspace"
"#
))
);
}
#[test]
fn deny_read_only_layers_do_not_leave_empty_permissions_tables() {
let path = if cfg!(windows) {
"C:\\secret"
} else {
"/secret"
};
let composed = compose(vec![layer(
"req_high",
"High",
&format!(
r#"
[permissions.filesystem]
deny_read = [{path:?}]
"#
),
)])
.expect("compose requirements")
.expect("requirements present");
assert_eq!(
composed,
expected_requirements(format!(
r#"
[permissions.filesystem]
deny_read = [{path:?}]
"#
))
);
}
#[test]
fn parse_error_names_layer() {
let err = compose(vec![layer(
"req_bad",
"Bad layer",
"allowed_approval_policies = [1]",
)])
.expect_err("invalid layer should fail");
assert!(err.to_string().contains("Bad layer (req_bad)"));
assert!(err.to_string().contains("allowed_approval_policies"));
}
+27 -6
View File
@@ -97,33 +97,47 @@ impl LoaderOverrides {
pub struct ConfigLayerEntry {
pub name: ConfigLayerSource,
pub config: TomlValue,
pub raw_toml: Option<String>,
pub version: String,
pub disabled_reason: Option<String>,
raw_toml: Option<RawTomlLayer>,
hooks_config_folder_override: Option<AbsolutePathBuf>,
}
#[derive(Debug, Clone, PartialEq)]
struct RawTomlLayer {
contents: String,
base_dir: AbsolutePathBuf,
}
impl ConfigLayerEntry {
pub fn new(name: ConfigLayerSource, config: TomlValue) -> Self {
let version = version_for_toml(&config);
Self {
name,
config,
raw_toml: None,
version,
disabled_reason: None,
raw_toml: None,
hooks_config_folder_override: None,
}
}
pub fn new_with_raw_toml(name: ConfigLayerSource, config: TomlValue, raw_toml: String) -> Self {
pub fn new_with_raw_toml(
name: ConfigLayerSource,
config: TomlValue,
raw_toml: String,
raw_toml_base_dir: AbsolutePathBuf,
) -> Self {
let version = version_for_toml(&config);
Self {
name,
config,
raw_toml: Some(raw_toml),
version,
disabled_reason: None,
raw_toml: Some(RawTomlLayer {
contents: raw_toml,
base_dir: raw_toml_base_dir,
}),
hooks_config_folder_override: None,
}
}
@@ -137,9 +151,9 @@ impl ConfigLayerEntry {
Self {
name,
config,
raw_toml: None,
version,
disabled_reason: Some(disabled_reason.into()),
raw_toml: None,
hooks_config_folder_override: None,
}
}
@@ -149,7 +163,13 @@ impl ConfigLayerEntry {
}
pub fn raw_toml(&self) -> Option<&str> {
self.raw_toml.as_deref()
self.raw_toml
.as_ref()
.map(|raw_toml| raw_toml.contents.as_str())
}
pub fn raw_toml_base_dir(&self) -> Option<&AbsolutePathBuf> {
self.raw_toml.as_ref().map(|raw_toml| &raw_toml.base_dir)
}
pub(crate) fn with_hooks_config_folder_override(
@@ -181,6 +201,7 @@ impl ConfigLayerEntry {
match &self.name {
ConfigLayerSource::Mdm { .. } => None,
ConfigLayerSource::System { file } => file.parent(),
ConfigLayerSource::EnterpriseManaged { .. } => None,
ConfigLayerSource::User { file, .. } => file.parent(),
ConfigLayerSource::Project { dot_codex_folder } => Some(dot_codex_folder.clone()),
ConfigLayerSource::SessionFlags => None,
+14 -2
View File
@@ -23,6 +23,9 @@ use serde::Serialize;
use serde::de::Error as SerdeError;
use std::collections::BTreeMap;
/// Highest function key supported by portable TUI keymap configuration.
pub const MAX_FUNCTION_KEY: u8 = 24;
/// Normalized string representation of a single key event (for example `ctrl-a`).
///
/// The parser accepts a small alias set (for example `escape` -> `esc`,
@@ -223,6 +226,8 @@ pub struct TuiVimNormalKeymap {
pub move_line_end: Option<KeybindingsSpec>,
/// Delete character under cursor (`x`).
pub delete_char: Option<KeybindingsSpec>,
/// Delete character under cursor and enter insert mode (`s`).
pub substitute_char: Option<KeybindingsSpec>,
/// Delete from cursor to end of line (`D`).
pub delete_to_line_end: Option<KeybindingsSpec>,
/// Change from cursor to end of line and enter insert mode (`C`).
@@ -550,14 +555,14 @@ fn normalize_key_name(key: &str, original: &str) -> Result<String, String> {
if let Some(number) = alias.strip_prefix('f')
&& let Ok(number) = number.parse::<u8>()
&& (1..=12).contains(&number)
&& (1..=MAX_FUNCTION_KEY).contains(&number)
{
return Ok(alias.to_string());
}
Err(format!(
"unknown key `{key}` in keybinding `{original}`. \
Use a printable character (for example `a`), function keys (`f1`-`f12`), \
Use a printable character (for example `a`), function keys (`f1`-`f{MAX_FUNCTION_KEY}`), \
or one of: enter, tab, backspace, esc, delete, arrows, home/end, page-up/page-down, space, minus.\n\
See the Codex keymap documentation for supported actions and examples."
))
@@ -672,4 +677,11 @@ mod tests {
assert_eq!(keymap, expected_keymap);
}
}
#[test]
fn function_keys_through_f24_are_accepted() {
assert_eq!(normalize_keybinding_spec("F13"), Ok("f13".to_string()));
assert_eq!(normalize_keybinding_spec("f24"), Ok("f24".to_string()));
assert!(normalize_keybinding_spec("f25").is_err());
}
}
+1
View File
@@ -31,6 +31,7 @@ use serde::Serialize;
pub use crate::tui_keymap::KeybindingSpec;
pub use crate::tui_keymap::KeybindingsSpec;
pub use crate::tui_keymap::MAX_FUNCTION_KEY;
pub use crate::tui_keymap::TuiApprovalKeymap;
pub use crate::tui_keymap::TuiChatKeymap;
pub use crate::tui_keymap::TuiComposerKeymap;
+1
View File
@@ -349,6 +349,7 @@ fn skill_roots_from_layer_stack_inner(
});
}
ConfigLayerSource::Mdm { .. }
| ConfigLayerSource::EnterpriseManaged { .. }
| ConfigLayerSource::SessionFlags
| ConfigLayerSource::LegacyManagedConfigTomlFromFile { .. }
| ConfigLayerSource::LegacyManagedConfigTomlFromMdm => {}
+23
View File
@@ -763,6 +763,16 @@
},
"type": "object"
},
"ExperimentalRequestUserInput": {
"additionalProperties": false,
"properties": {
"enabled": {
"default": true,
"type": "boolean"
}
},
"type": "object"
},
"ExternalConfigMigrationPrompts": {
"additionalProperties": false,
"description": "Settings for notices we display to users via the tui and app-server clients (primarily the Codex IDE extension). NOTE: these are different from notifications - notices are warnings, NUX screens, acknowledgements, etc.",
@@ -2712,6 +2722,9 @@
"ToolsToml": {
"additionalProperties": false,
"properties": {
"experimental_request_user_input": {
"$ref": "#/definitions/ExperimentalRequestUserInput"
},
"web_search": {
"allOf": [
{
@@ -2858,6 +2871,7 @@
"start_change_operator": null,
"start_delete_operator": null,
"start_yank_operator": null,
"substitute_char": null,
"yank_line": null
},
"vim_operator": {
@@ -3548,6 +3562,7 @@
"start_change_operator": null,
"start_delete_operator": null,
"start_yank_operator": null,
"substitute_char": null,
"yank_line": null
}
},
@@ -3975,6 +3990,14 @@
],
"description": "Begin yank operator; next key selects motion (`y`)."
},
"substitute_char": {
"allOf": [
{
"$ref": "#/definitions/KeybindingsSpec"
}
],
"description": "Delete character under cursor and enter insert mode (`s`)."
},
"yank_line": {
"allOf": [
{
+1 -1
View File
@@ -32,5 +32,5 @@ fn register_session_root(session: &Arc<Session>, turn: &Arc<TurnContext>) {
session
.services
.agent_control
.register_session_root(session.conversation_id, &turn.session_source);
.register_session_root(session.conversation_id, turn.parent_thread_id);
}
+13 -15
View File
@@ -54,6 +54,7 @@ pub(crate) enum SpawnAgentForkMode {
pub(crate) struct SpawnAgentOptions {
pub(crate) fork_parent_spawn_call_id: Option<String>,
pub(crate) fork_mode: Option<SpawnAgentForkMode>,
pub(crate) parent_thread_id: Option<ThreadId>,
pub(crate) environments: Option<Vec<TurnEnvironmentSelection>>,
}
@@ -262,12 +263,12 @@ impl AgentControl {
.await?
}
(Some(session_source), None) => {
let forked_from_thread_id = thread_spawn_parent_thread_id(&session_source);
Box::pin(state.spawn_new_thread_with_source(
config.clone(),
self.clone(),
session_source,
forked_from_thread_id,
options.parent_thread_id,
/*forked_from_thread_id*/ None,
/*thread_source*/ Some(ThreadSource::Subagent),
/*persist_extended_history*/ false,
/*metrics_service_name*/ None,
@@ -309,6 +310,7 @@ impl AgentControl {
}
};
let thread_config = new_thread.thread.codex.thread_config_snapshot().await;
let parent_thread_id = thread_config.parent_thread_id;
emit_subagent_session_started(
&new_thread
.thread
@@ -319,7 +321,7 @@ impl AgentControl {
client_metadata,
new_thread.thread.codex.session.session_id(),
new_thread.thread_id,
/*parent_thread_id*/ None,
parent_thread_id,
thread_config,
subagent_source.clone(),
);
@@ -473,6 +475,7 @@ impl AgentControl {
}
if preserve_reference_context_item
&& config.features.enabled(Feature::MultiAgentV2)
&& config.multi_agent_v2.usage_hint_enabled
&& let Some(subagent_usage_hint_text) =
config.multi_agent_v2.subagent_usage_hint_text.clone()
&& let Some(subagent_usage_hint_message) =
@@ -490,6 +493,7 @@ impl AgentControl {
self.clone(),
session_source,
/*thread_source*/ Some(ThreadSource::Subagent),
/*parent_thread_id*/ Some(parent_thread_id),
/*forked_from_thread_id*/ Some(parent_thread_id),
/*persist_extended_history*/ false,
inherited_shell_snapshot,
@@ -638,6 +642,7 @@ impl AgentControl {
.history
.ok_or_else(|| CodexErr::ThreadNotFound(thread_id))?
.items;
let parent_thread_id = stored_thread.parent_thread_id;
let resumed_thread = state
.resume_thread_with_history_with_source(ResumeThreadWithHistoryOptions {
@@ -649,6 +654,7 @@ impl AgentControl {
}),
agent_control: self.clone(),
session_source,
parent_thread_id,
inherited_shell_snapshot,
inherited_exec_policy,
})
@@ -841,9 +847,9 @@ impl AgentControl {
pub(crate) fn register_session_root(
&self,
current_thread_id: ThreadId,
current_session_source: &SessionSource,
current_parent_thread_id: Option<ThreadId>,
) {
if thread_spawn_parent_thread_id(current_session_source).is_none() {
if current_parent_thread_id.is_none() {
self.state.register_root_thread(current_thread_id);
}
}
@@ -1218,7 +1224,8 @@ impl AgentControl {
child_thread_id: ThreadId,
session_source: Option<&SessionSource>,
) {
let Some(parent_thread_id) = session_source.and_then(thread_spawn_parent_thread_id) else {
let Some(parent_thread_id) = session_source.and_then(SessionSource::parent_thread_id)
else {
return;
};
let Some(state_db_ctx) = thread.state_db() else {
@@ -1263,15 +1270,6 @@ impl AgentControl {
}
}
fn thread_spawn_parent_thread_id(session_source: &SessionSource) -> Option<ThreadId> {
match session_source {
SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
parent_thread_id, ..
}) => Some(*parent_thread_id),
_ => None,
}
}
fn agent_matches_prefix(agent_path: Option<&AgentPath>, prefix: &AgentPath) -> bool {
if prefix.is_root() {
return true;
+61
View File
@@ -74,6 +74,15 @@ fn assistant_message(text: &str, phase: Option<MessagePhase>) -> ResponseItem {
}
}
#[test]
fn register_session_root_skips_threads_with_explicit_parent() {
let control = AgentControl::default();
control.register_session_root(ThreadId::new(), Some(ThreadId::new()));
assert_eq!(control.state.agent_id_for_path(&AgentPath::root()), None);
}
fn spawn_agent_call(call_id: &str) -> ResponseItem {
ResponseItem::FunctionCall {
id: None,
@@ -708,6 +717,53 @@ async fn spawn_agent_can_fork_parent_thread_history_with_sanitized_items() {
"full-history forked child should preserve the parent diff baseline"
);
let mut disabled_hint_child_config = harness.config.clone();
let _ = disabled_hint_child_config
.features
.enable(Feature::MultiAgentV2);
disabled_hint_child_config.multi_agent_v2.usage_hint_enabled = false;
disabled_hint_child_config
.multi_agent_v2
.subagent_usage_hint_text = Some("Disabled child subagent guidance.".to_string());
let disabled_hint_child_thread_id = harness
.control
.spawn_agent_with_metadata(
disabled_hint_child_config,
text_input("child task without hints"),
Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
parent_thread_id,
depth: 1,
agent_path: None,
agent_nickname: None,
agent_role: None,
})),
SpawnAgentOptions {
fork_parent_spawn_call_id: Some(parent_spawn_call_id.clone()),
fork_mode: Some(SpawnAgentForkMode::FullHistory),
..Default::default()
},
)
.await
.expect("forked spawn should honor disabled usage hints")
.thread_id;
let disabled_hint_child_thread = harness
.manager
.get_thread(disabled_hint_child_thread_id)
.await
.expect("disabled-hint child thread should be registered");
let disabled_hint_history = disabled_hint_child_thread
.codex
.session
.clone_history()
.await;
assert!(
!history_contains_text(
disabled_hint_history.raw_items(),
"Disabled child subagent guidance.",
),
"full-history forked child should not add subagent guidance when usage hints are disabled"
);
let expected = (
child_thread_id,
Op::UserInput {
@@ -734,6 +790,11 @@ async fn spawn_agent_can_fork_parent_thread_history_with_sanitized_items() {
.shutdown_live_agent(child_thread_id)
.await
.expect("child shutdown should submit");
let _ = harness
.control
.shutdown_live_agent(disabled_hint_child_thread_id)
.await
.expect("disabled-hint child shutdown should submit");
let _ = parent_thread
.submit(Op::Shutdown {})
.await
+7 -16
View File
@@ -173,6 +173,7 @@ struct ModelClientState {
provider: SharedModelProvider,
auth_env_telemetry: AuthEnvTelemetry,
session_source: SessionSource,
parent_thread_id: Option<ThreadId>,
model_verbosity: Option<VerbosityConfig>,
enable_request_compression: bool,
include_timing_metrics: bool,
@@ -321,6 +322,7 @@ impl ModelClient {
installation_id: String,
provider_info: ModelProviderInfo,
session_source: SessionSource,
parent_thread_id: Option<ThreadId>,
model_verbosity: Option<VerbosityConfig>,
enable_request_compression: bool,
include_timing_metrics: bool,
@@ -344,6 +346,7 @@ impl ModelClient {
provider: model_provider,
auth_env_telemetry,
session_source,
parent_thread_id,
model_verbosity,
enable_request_compression,
include_timing_metrics,
@@ -637,7 +640,7 @@ impl ModelClient {
fn build_responses_identity_headers(&self) -> ApiHeaderMap {
let mut extra_headers = self.build_subagent_headers();
if let Some(parent_thread_id) = parent_thread_id_header_value(&self.state.session_source)
if let Some(parent_thread_id) = parent_thread_id_header_value(self.state.parent_thread_id)
&& let Ok(val) = HeaderValue::from_str(&parent_thread_id)
{
extra_headers.insert(X_CODEX_PARENT_THREAD_ID_HEADER, val);
@@ -664,7 +667,7 @@ impl ModelClient {
if let Some(subagent) = subagent_header_value(&self.state.session_source) {
client_metadata.insert(X_OPENAI_SUBAGENT_HEADER.to_string(), subagent);
}
if let Some(parent_thread_id) = parent_thread_id_header_value(&self.state.session_source) {
if let Some(parent_thread_id) = parent_thread_id_header_value(self.state.parent_thread_id) {
client_metadata.insert(
X_CODEX_PARENT_THREAD_ID_HEADER.to_string(),
parent_thread_id,
@@ -1733,20 +1736,8 @@ fn subagent_header_value(session_source: &SessionSource) -> Option<String> {
}
}
fn parent_thread_id_header_value(session_source: &SessionSource) -> Option<String> {
match session_source {
SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
parent_thread_id, ..
}) => Some(parent_thread_id.to_string()),
SessionSource::Cli
| SessionSource::VSCode
| SessionSource::Exec
| SessionSource::Mcp
| SessionSource::Custom(_)
| SessionSource::Internal(_)
| SessionSource::SubAgent(_)
| SessionSource::Unknown => None,
}
fn parent_thread_id_header_value(parent_thread_id: Option<ThreadId>) -> Option<String> {
parent_thread_id.map(|parent_thread_id| parent_thread_id.to_string())
}
const RESPONSE_STREAM_CHANNEL_CAPACITY: usize = 1600;

Some files were not shown because too many files have changed in this diff Show More