diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 97591d4c19..25dff134a7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,6 +26,9 @@ jobs: - name: Verify Bazel clippy flags match Cargo workspace lints run: python3 .github/scripts/verify_bazel_clippy_lints.py + - name: Test Codex package builder + run: python3 -m unittest discover -s scripts/codex_package -p 'test_*.py' + - name: Setup pnpm uses: pnpm/action-setup@a8198c4bff370c8506180b035930dea56dbd5288 # v5 with: diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index 571ab3c33e..02d7c76a91 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -1799,7 +1799,6 @@ "winnow_0.7.15": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"annotate-snippets\",\"req\":\"^0.11.4\"},{\"name\":\"anstream\",\"optional\":true,\"req\":\"^0.6.15\"},{\"name\":\"anstyle\",\"optional\":true,\"req\":\"^1.0.8\"},{\"kind\":\"dev\",\"name\":\"anyhow\",\"req\":\"^1.0.100\"},{\"kind\":\"dev\",\"name\":\"automod\",\"req\":\"^1.0.15\"},{\"kind\":\"dev\",\"name\":\"circular\",\"req\":\"^0.3.0\"},{\"kind\":\"dev\",\"name\":\"criterion\",\"req\":\"^0.5.1\"},{\"name\":\"is_terminal_polyfill\",\"optional\":true,\"req\":\"^1.48.1\"},{\"kind\":\"dev\",\"name\":\"lexopt\",\"req\":\"^0.3.1\"},{\"default_features\":false,\"name\":\"memchr\",\"optional\":true,\"req\":\"^2.7\"},{\"kind\":\"dev\",\"name\":\"proptest\",\"req\":\"^1.6.0\"},{\"kind\":\"dev\",\"name\":\"rustc-hash\",\"req\":\"^2.1.1\"},{\"features\":[\"examples\"],\"kind\":\"dev\",\"name\":\"snapbox\",\"req\":\"^0.6.21\"},{\"kind\":\"dev\",\"name\":\"term-transcript\",\"req\":\"^0.2.0\"},{\"name\":\"terminal_size\",\"optional\":true,\"req\":\"^0.4.3\"}],\"features\":{\"alloc\":[],\"debug\":[\"std\",\"dep:anstream\",\"dep:anstyle\",\"dep:is_terminal_polyfill\",\"dep:terminal_size\"],\"default\":[\"std\"],\"simd\":[\"dep:memchr\"],\"std\":[\"alloc\",\"memchr?/std\"],\"unstable-doc\":[\"alloc\",\"std\",\"simd\",\"unstable-recover\"],\"unstable-recover\":[]}}", "winreg_0.10.1": "{\"dependencies\":[{\"name\":\"chrono\",\"optional\":true,\"req\":\"^0.4.6\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.3\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"serde_derive\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"~3.0\"},{\"features\":[\"impl-default\",\"impl-debug\",\"minwindef\",\"minwinbase\",\"timezoneapi\",\"winerror\",\"winnt\",\"winreg\",\"handleapi\"],\"name\":\"winapi\",\"req\":\"^0.3.9\"}],\"features\":{\"serialization-serde\":[\"transactions\",\"serde\"],\"transactions\":[\"winapi/ktmw32\"]}}", "winreg_0.50.0": "{\"dependencies\":[{\"name\":\"cfg-if\",\"req\":\"^1.0\"},{\"name\":\"chrono\",\"optional\":true,\"req\":\"^0.4.6\"},{\"kind\":\"dev\",\"name\":\"rand\",\"req\":\"^0.3\"},{\"name\":\"serde\",\"optional\":true,\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"serde_bytes\",\"req\":\"^0.11\"},{\"kind\":\"dev\",\"name\":\"serde_derive\",\"req\":\"^1\"},{\"kind\":\"dev\",\"name\":\"tempfile\",\"req\":\"~3.0\"},{\"features\":[\"Win32_Foundation\",\"Win32_System_Time\",\"Win32_System_Registry\",\"Win32_Security\",\"Win32_Storage_FileSystem\",\"Win32_System_Diagnostics_Debug\"],\"name\":\"windows-sys\",\"req\":\"^0.48.0\"}],\"features\":{\"serialization-serde\":[\"transactions\",\"serde\"],\"transactions\":[]}}", - "winres_0.1.12": "{\"dependencies\":[{\"name\":\"toml\",\"req\":\"^0.5\"},{\"features\":[\"winnt\"],\"kind\":\"dev\",\"name\":\"winapi\",\"req\":\"^0.3\"}],\"features\":{}}", "winsafe_0.0.19": "{\"dependencies\":[],\"features\":{\"comctl\":[\"ole\"],\"dshow\":[\"oleaut\"],\"dwm\":[\"uxtheme\"],\"dxgi\":[\"ole\"],\"gdi\":[\"user\"],\"gui\":[\"comctl\",\"shell\",\"uxtheme\"],\"kernel\":[],\"mf\":[\"oleaut\"],\"ole\":[\"user\"],\"oleaut\":[\"ole\"],\"shell\":[\"oleaut\"],\"taskschd\":[\"oleaut\"],\"user\":[\"kernel\"],\"uxtheme\":[\"gdi\",\"ole\"],\"version\":[\"kernel\"]}}", "winsplit_0.1.0": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"doc-comment\",\"req\":\"^0.3.3\"}],\"features\":{\"default\":[\"std\"],\"std\":[]}}", "wiremock_0.6.5": "{\"dependencies\":[{\"kind\":\"dev\",\"name\":\"actix-rt\",\"req\":\"^2.10.0\"},{\"name\":\"assert-json-diff\",\"req\":\"^2.0.2\"},{\"features\":[\"attributes\",\"tokio1\"],\"kind\":\"dev\",\"name\":\"async-std\",\"req\":\"^1.13.2\"},{\"name\":\"base64\",\"req\":\"^0.22\"},{\"name\":\"deadpool\",\"req\":\"^0.12.2\"},{\"name\":\"futures\",\"req\":\"^0.3.31\"},{\"name\":\"http\",\"req\":\"^1.3\"},{\"name\":\"http-body-util\",\"req\":\"^0.1\"},{\"features\":[\"full\"],\"name\":\"hyper\",\"req\":\"^1.7\"},{\"features\":[\"tokio\",\"server\",\"http1\",\"http2\"],\"name\":\"hyper-util\",\"req\":\"^0.1\"},{\"name\":\"log\",\"req\":\"^0.4\"},{\"name\":\"once_cell\",\"req\":\"^1\"},{\"name\":\"regex\",\"req\":\"^1\"},{\"features\":[\"json\"],\"kind\":\"dev\",\"name\":\"reqwest\",\"req\":\"^0.12.23\"},{\"name\":\"serde\",\"req\":\"^1\"},{\"features\":[\"derive\"],\"kind\":\"dev\",\"name\":\"serde\",\"req\":\"^1\"},{\"name\":\"serde_json\",\"req\":\"^1\"},{\"features\":[\"rt\",\"macros\",\"net\"],\"name\":\"tokio\",\"req\":\"^1.47.1\"},{\"features\":[\"macros\",\"rt-multi-thread\"],\"kind\":\"dev\",\"name\":\"tokio\",\"req\":\"^1.47.1\"},{\"name\":\"url\",\"req\":\"^2.5\"}],\"features\":{}}", diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 823eb6d3c1..476a38a9dd 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -2434,6 +2434,7 @@ dependencies = [ "dunce", "futures", "gethostname", + "indexmap 2.13.0", "libc", "multimap", "pretty_assertions", @@ -4142,7 +4143,6 @@ dependencies = [ "tokio", "windows 0.58.0", "windows-sys 0.52.0", - "winres", ] [[package]] @@ -14727,15 +14727,6 @@ dependencies = [ "windows-sys 0.48.0", ] -[[package]] -name = "winres" -version = "0.1.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b68db261ef59e9e52806f688020631e987592bd83619edccda9c47d42cde4f6c" -dependencies = [ - "toml 0.5.11", -] - [[package]] name = "winsafe" version = "0.0.19" diff --git a/codex-rs/analytics/src/analytics_client_tests.rs b/codex-rs/analytics/src/analytics_client_tests.rs index c744eb3f6e..ef5051caba 100644 --- a/codex-rs/analytics/src/analytics_client_tests.rs +++ b/codex-rs/analytics/src/analytics_client_tests.rs @@ -3628,6 +3628,7 @@ async fn turn_event_counts_completed_tool_items() { status: McpToolCallStatus::Completed, arguments: json!({}), mcp_app_resource_uri: None, + plugin_id: None, result: None, error: None, duration_ms: Some(2), diff --git a/codex-rs/analytics/src/events.rs b/codex-rs/analytics/src/events.rs index f7c64e0e74..87cb165ac2 100644 --- a/codex-rs/analytics/src/events.rs +++ b/codex-rs/analytics/src/events.rs @@ -991,6 +991,7 @@ fn analytics_hook_event_name(event_name: HookEventName) -> &'static str { HookEventName::SessionStart => "SessionStart", HookEventName::UserPromptSubmit => "UserPromptSubmit", HookEventName::SubagentStart => "SubagentStart", + HookEventName::SubagentStop => "SubagentStop", HookEventName::Stop => "Stop", } } diff --git a/codex-rs/app-server-protocol/schema/json/ClientRequest.json b/codex-rs/app-server-protocol/schema/json/ClientRequest.json index 788e52e82b..97b5f698c2 100644 --- a/codex-rs/app-server-protocol/schema/json/ClientRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ClientRequest.json @@ -3156,6 +3156,62 @@ ], "type": "object" }, + "ThreadGoalClearParams": { + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "type": "object" + }, + "ThreadGoalGetParams": { + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "type": "object" + }, + "ThreadGoalSetParams": { + "properties": { + "objective": { + "type": [ + "string", + "null" + ] + }, + "status": { + "anyOf": [ + { + "$ref": "#/definitions/ThreadGoalStatus" + }, + { + "type": "null" + } + ] + }, + "threadId": { + "type": "string" + }, + "tokenBudget": { + "format": "int64", + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "threadId" + ], + "type": "object" + }, "ThreadGoalStatus": { "enum": [ "active", @@ -4316,6 +4372,78 @@ "title": "Thread/name/setRequest", "type": "object" }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/goal/set" + ], + "title": "Thread/goal/setRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadGoalSetParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/goal/setRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/goal/get" + ], + "title": "Thread/goal/getRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadGoalGetParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/goal/getRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/goal/clear" + ], + "title": "Thread/goal/clearRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadGoalClearParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/goal/clearRequest", + "type": "object" + }, { "properties": { "id": { diff --git a/codex-rs/app-server-protocol/schema/json/ServerNotification.json b/codex-rs/app-server-protocol/schema/json/ServerNotification.json index 9270af85e7..90899cb152 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerNotification.json +++ b/codex-rs/app-server-protocol/schema/json/ServerNotification.json @@ -1836,6 +1836,7 @@ "sessionStart", "userPromptSubmit", "subagentStart", + "subagentStop", "stop" ], "type": "string" @@ -3860,6 +3861,12 @@ "null" ] }, + "pluginId": { + "type": [ + "string", + "null" + ] + }, "result": { "anyOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index b0158d0a19..c7a7989fbc 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -372,6 +372,78 @@ "title": "Thread/name/setRequest", "type": "object" }, + { + "properties": { + "id": { + "$ref": "#/definitions/v2/RequestId" + }, + "method": { + "enum": [ + "thread/goal/set" + ], + "title": "Thread/goal/setRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/v2/ThreadGoalSetParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/goal/setRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/v2/RequestId" + }, + "method": { + "enum": [ + "thread/goal/get" + ], + "title": "Thread/goal/getRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/v2/ThreadGoalGetParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/goal/getRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/v2/RequestId" + }, + "method": { + "enum": [ + "thread/goal/clear" + ], + "title": "Thread/goal/clearRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/v2/ThreadGoalClearParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/goal/clearRequest", + "type": "object" + }, { "properties": { "id": { @@ -9710,6 +9782,7 @@ "sessionStart", "userPromptSubmit", "subagentStart", + "subagentStop", "stop" ], "type": "string" @@ -10606,6 +10679,12 @@ }, "type": "array" }, + "SubagentStop": { + "items": { + "$ref": "#/definitions/v2/ConfiguredHookMatcherGroup" + }, + "type": "array" + }, "UserPromptSubmit": { "items": { "$ref": "#/definitions/v2/ConfiguredHookMatcherGroup" @@ -10634,6 +10713,7 @@ "SessionStart", "Stop", "SubagentStart", + "SubagentStop", "UserPromptSubmit" ], "type": "object" @@ -11266,6 +11346,14 @@ "defaultReasoningEffort": { "$ref": "#/definitions/v2/ReasoningEffort" }, + "defaultServiceTier": { + "default": null, + "description": "Catalog default service tier id for this model, when one is configured.", + "type": [ + "string", + "null" + ] + }, "description": { "type": "string" }, @@ -15746,6 +15834,32 @@ ], "type": "object" }, + "ThreadGoalClearParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadGoalClearParams", + "type": "object" + }, + "ThreadGoalClearResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "cleared": { + "type": "boolean" + } + }, + "required": [ + "cleared" + ], + "title": "ThreadGoalClearResponse", + "type": "object" + }, "ThreadGoalClearedNotification": { "$schema": "http://json-schema.org/draft-07/schema#", "properties": { @@ -15759,6 +15873,85 @@ "title": "ThreadGoalClearedNotification", "type": "object" }, + "ThreadGoalGetParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadGoalGetParams", + "type": "object" + }, + "ThreadGoalGetResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "goal": { + "anyOf": [ + { + "$ref": "#/definitions/v2/ThreadGoal" + }, + { + "type": "null" + } + ] + } + }, + "title": "ThreadGoalGetResponse", + "type": "object" + }, + "ThreadGoalSetParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "objective": { + "type": [ + "string", + "null" + ] + }, + "status": { + "anyOf": [ + { + "$ref": "#/definitions/v2/ThreadGoalStatus" + }, + { + "type": "null" + } + ] + }, + "threadId": { + "type": "string" + }, + "tokenBudget": { + "format": "int64", + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "threadId" + ], + "title": "ThreadGoalSetParams", + "type": "object" + }, + "ThreadGoalSetResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "goal": { + "$ref": "#/definitions/v2/ThreadGoal" + } + }, + "required": [ + "goal" + ], + "title": "ThreadGoalSetResponse", + "type": "object" + }, "ThreadGoalStatus": { "enum": [ "active", @@ -16126,6 +16319,12 @@ "null" ] }, + "pluginId": { + "type": [ + "string", + "null" + ] + }, "result": { "anyOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index 7e0053dcf2..7da34ca00c 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -1098,6 +1098,78 @@ "title": "Thread/name/setRequest", "type": "object" }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/goal/set" + ], + "title": "Thread/goal/setRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadGoalSetParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/goal/setRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/goal/get" + ], + "title": "Thread/goal/getRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadGoalGetParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/goal/getRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "thread/goal/clear" + ], + "title": "Thread/goal/clearRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/ThreadGoalClearParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Thread/goal/clearRequest", + "type": "object" + }, { "properties": { "id": { @@ -6190,6 +6262,7 @@ "sessionStart", "userPromptSubmit", "subagentStart", + "subagentStop", "stop" ], "type": "string" @@ -7135,6 +7208,12 @@ }, "type": "array" }, + "SubagentStop": { + "items": { + "$ref": "#/definitions/ConfiguredHookMatcherGroup" + }, + "type": "array" + }, "UserPromptSubmit": { "items": { "$ref": "#/definitions/ConfiguredHookMatcherGroup" @@ -7163,6 +7242,7 @@ "SessionStart", "Stop", "SubagentStart", + "SubagentStop", "UserPromptSubmit" ], "type": "object" @@ -7795,6 +7875,14 @@ "defaultReasoningEffort": { "$ref": "#/definitions/ReasoningEffort" }, + "defaultServiceTier": { + "default": null, + "description": "Catalog default service tier id for this model, when one is configured.", + "type": [ + "string", + "null" + ] + }, "description": { "type": "string" }, @@ -13570,6 +13658,32 @@ ], "type": "object" }, + "ThreadGoalClearParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadGoalClearParams", + "type": "object" + }, + "ThreadGoalClearResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "cleared": { + "type": "boolean" + } + }, + "required": [ + "cleared" + ], + "title": "ThreadGoalClearResponse", + "type": "object" + }, "ThreadGoalClearedNotification": { "$schema": "http://json-schema.org/draft-07/schema#", "properties": { @@ -13583,6 +13697,85 @@ "title": "ThreadGoalClearedNotification", "type": "object" }, + "ThreadGoalGetParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadGoalGetParams", + "type": "object" + }, + "ThreadGoalGetResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "goal": { + "anyOf": [ + { + "$ref": "#/definitions/ThreadGoal" + }, + { + "type": "null" + } + ] + } + }, + "title": "ThreadGoalGetResponse", + "type": "object" + }, + "ThreadGoalSetParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "objective": { + "type": [ + "string", + "null" + ] + }, + "status": { + "anyOf": [ + { + "$ref": "#/definitions/ThreadGoalStatus" + }, + { + "type": "null" + } + ] + }, + "threadId": { + "type": "string" + }, + "tokenBudget": { + "format": "int64", + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "threadId" + ], + "title": "ThreadGoalSetParams", + "type": "object" + }, + "ThreadGoalSetResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "goal": { + "$ref": "#/definitions/ThreadGoal" + } + }, + "required": [ + "goal" + ], + "title": "ThreadGoalSetResponse", + "type": "object" + }, "ThreadGoalStatus": { "enum": [ "active", @@ -13950,6 +14143,12 @@ "null" ] }, + "pluginId": { + "type": [ + "string", + "null" + ] + }, "result": { "anyOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json index 3515b5d1d1..761177ea4c 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json @@ -288,6 +288,12 @@ }, "type": "array" }, + "SubagentStop": { + "items": { + "$ref": "#/definitions/ConfiguredHookMatcherGroup" + }, + "type": "array" + }, "UserPromptSubmit": { "items": { "$ref": "#/definitions/ConfiguredHookMatcherGroup" @@ -316,6 +322,7 @@ "SessionStart", "Stop", "SubagentStart", + "SubagentStop", "UserPromptSubmit" ], "type": "object" diff --git a/codex-rs/app-server-protocol/schema/json/v2/HookCompletedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/HookCompletedNotification.json index 164b4865fb..088da47484 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/HookCompletedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/HookCompletedNotification.json @@ -15,6 +15,7 @@ "sessionStart", "userPromptSubmit", "subagentStart", + "subagentStop", "stop" ], "type": "string" diff --git a/codex-rs/app-server-protocol/schema/json/v2/HookStartedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/HookStartedNotification.json index 924d522a82..38395cded9 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/HookStartedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/HookStartedNotification.json @@ -15,6 +15,7 @@ "sessionStart", "userPromptSubmit", "subagentStart", + "subagentStop", "stop" ], "type": "string" diff --git a/codex-rs/app-server-protocol/schema/json/v2/HooksListResponse.json b/codex-rs/app-server-protocol/schema/json/v2/HooksListResponse.json index 913962b603..c58a5c767d 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/HooksListResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/HooksListResponse.json @@ -30,6 +30,7 @@ "sessionStart", "userPromptSubmit", "subagentStart", + "subagentStop", "stop" ], "type": "string" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ItemCompletedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/ItemCompletedNotification.json index 7aed9d9722..87d36d2927 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ItemCompletedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ItemCompletedNotification.json @@ -800,6 +800,12 @@ "null" ] }, + "pluginId": { + "type": [ + "string", + "null" + ] + }, "result": { "anyOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ItemStartedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/ItemStartedNotification.json index 80a3cd2425..d45fddf4ba 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ItemStartedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ItemStartedNotification.json @@ -800,6 +800,12 @@ "null" ] }, + "pluginId": { + "type": [ + "string", + "null" + ] + }, "result": { "anyOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ModelListResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ModelListResponse.json index c0221805eb..32ec2e7679 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ModelListResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ModelListResponse.json @@ -43,6 +43,14 @@ "defaultReasoningEffort": { "$ref": "#/definitions/ReasoningEffort" }, + "defaultServiceTier": { + "default": null, + "description": "Catalog default service tier id for this model, when one is configured.", + "type": [ + "string", + "null" + ] + }, "description": { "type": "string" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/PluginReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/PluginReadResponse.json index 6d2a0b5d56..c9fe43c34f 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/PluginReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/PluginReadResponse.json @@ -47,6 +47,7 @@ "sessionStart", "userPromptSubmit", "subagentStart", + "subagentStop", "stop" ], "type": "string" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ReviewStartResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ReviewStartResponse.json index 882fa1f598..877eeb1278 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ReviewStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ReviewStartResponse.json @@ -944,6 +944,12 @@ "null" ] }, + "pluginId": { + "type": [ + "string", + "null" + ] + }, "result": { "anyOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json index cccc7e5b8d..8c45f57d38 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json @@ -1421,6 +1421,12 @@ "null" ] }, + "pluginId": { + "type": [ + "string", + "null" + ] + }, "result": { "anyOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadGoalClearParams.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadGoalClearParams.json new file mode 100644 index 0000000000..99b32a7316 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadGoalClearParams.json @@ -0,0 +1,13 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadGoalClearParams", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadGoalClearResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadGoalClearResponse.json new file mode 100644 index 0000000000..42c3a50ac1 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadGoalClearResponse.json @@ -0,0 +1,13 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "cleared": { + "type": "boolean" + } + }, + "required": [ + "cleared" + ], + "title": "ThreadGoalClearResponse", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadGoalGetParams.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadGoalGetParams.json new file mode 100644 index 0000000000..631e06a990 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadGoalGetParams.json @@ -0,0 +1,13 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "properties": { + "threadId": { + "type": "string" + } + }, + "required": [ + "threadId" + ], + "title": "ThreadGoalGetParams", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadGoalGetResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadGoalGetResponse.json new file mode 100644 index 0000000000..7627276e11 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadGoalGetResponse.json @@ -0,0 +1,76 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "definitions": { + "ThreadGoal": { + "properties": { + "createdAt": { + "format": "int64", + "type": "integer" + }, + "objective": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/ThreadGoalStatus" + }, + "threadId": { + "type": "string" + }, + "timeUsedSeconds": { + "format": "int64", + "type": "integer" + }, + "tokenBudget": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "tokensUsed": { + "format": "int64", + "type": "integer" + }, + "updatedAt": { + "format": "int64", + "type": "integer" + } + }, + "required": [ + "createdAt", + "objective", + "status", + "threadId", + "timeUsedSeconds", + "tokensUsed", + "updatedAt" + ], + "type": "object" + }, + "ThreadGoalStatus": { + "enum": [ + "active", + "paused", + "blocked", + "usageLimited", + "budgetLimited", + "complete" + ], + "type": "string" + } + }, + "properties": { + "goal": { + "anyOf": [ + { + "$ref": "#/definitions/ThreadGoal" + }, + { + "type": "null" + } + ] + } + }, + "title": "ThreadGoalGetResponse", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadGoalSetParams.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadGoalSetParams.json new file mode 100644 index 0000000000..0087827c21 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadGoalSetParams.json @@ -0,0 +1,49 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "definitions": { + "ThreadGoalStatus": { + "enum": [ + "active", + "paused", + "blocked", + "usageLimited", + "budgetLimited", + "complete" + ], + "type": "string" + } + }, + "properties": { + "objective": { + "type": [ + "string", + "null" + ] + }, + "status": { + "anyOf": [ + { + "$ref": "#/definitions/ThreadGoalStatus" + }, + { + "type": "null" + } + ] + }, + "threadId": { + "type": "string" + }, + "tokenBudget": { + "format": "int64", + "type": [ + "integer", + "null" + ] + } + }, + "required": [ + "threadId" + ], + "title": "ThreadGoalSetParams", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadGoalSetResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadGoalSetResponse.json new file mode 100644 index 0000000000..a0d17a84a2 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadGoalSetResponse.json @@ -0,0 +1,72 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "definitions": { + "ThreadGoal": { + "properties": { + "createdAt": { + "format": "int64", + "type": "integer" + }, + "objective": { + "type": "string" + }, + "status": { + "$ref": "#/definitions/ThreadGoalStatus" + }, + "threadId": { + "type": "string" + }, + "timeUsedSeconds": { + "format": "int64", + "type": "integer" + }, + "tokenBudget": { + "format": "int64", + "type": [ + "integer", + "null" + ] + }, + "tokensUsed": { + "format": "int64", + "type": "integer" + }, + "updatedAt": { + "format": "int64", + "type": "integer" + } + }, + "required": [ + "createdAt", + "objective", + "status", + "threadId", + "timeUsedSeconds", + "tokensUsed", + "updatedAt" + ], + "type": "object" + }, + "ThreadGoalStatus": { + "enum": [ + "active", + "paused", + "blocked", + "usageLimited", + "budgetLimited", + "complete" + ], + "type": "string" + } + }, + "properties": { + "goal": { + "$ref": "#/definitions/ThreadGoal" + } + }, + "required": [ + "goal" + ], + "title": "ThreadGoalSetResponse", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json index 0693b19028..a9a186228b 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadListResponse.json @@ -1236,6 +1236,12 @@ "null" ] }, + "pluginId": { + "type": [ + "string", + "null" + ] + }, "result": { "anyOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json index d2e4ca6728..a2a4834cb3 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadMetadataUpdateResponse.json @@ -1236,6 +1236,12 @@ "null" ] }, + "pluginId": { + "type": [ + "string", + "null" + ] + }, "result": { "anyOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json index 431ca759de..5d76f9b181 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadReadResponse.json @@ -1236,6 +1236,12 @@ "null" ] }, + "pluginId": { + "type": [ + "string", + "null" + ] + }, "result": { "anyOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json index f57257f94c..8055ff58fc 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json @@ -1421,6 +1421,12 @@ "null" ] }, + "pluginId": { + "type": [ + "string", + "null" + ] + }, "result": { "anyOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json index 8d807d76cb..d0e25a1eaa 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadRollbackResponse.json @@ -1236,6 +1236,12 @@ "null" ] }, + "pluginId": { + "type": [ + "string", + "null" + ] + }, "result": { "anyOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json index 02d156d7a6..d456ccebc4 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json @@ -1421,6 +1421,12 @@ "null" ] }, + "pluginId": { + "type": [ + "string", + "null" + ] + }, "result": { "anyOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json index 3ec843e817..dd7de34b82 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartedNotification.json @@ -1236,6 +1236,12 @@ "null" ] }, + "pluginId": { + "type": [ + "string", + "null" + ] + }, "result": { "anyOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json index ea48e34180..5929510520 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadUnarchiveResponse.json @@ -1236,6 +1236,12 @@ "null" ] }, + "pluginId": { + "type": [ + "string", + "null" + ] + }, "result": { "anyOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v2/TurnCompletedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/TurnCompletedNotification.json index 40b81e5a34..ddaab863f7 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/TurnCompletedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/TurnCompletedNotification.json @@ -944,6 +944,12 @@ "null" ] }, + "pluginId": { + "type": [ + "string", + "null" + ] + }, "result": { "anyOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v2/TurnStartResponse.json b/codex-rs/app-server-protocol/schema/json/v2/TurnStartResponse.json index ffe0a28d15..a2836f7f03 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/TurnStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/TurnStartResponse.json @@ -944,6 +944,12 @@ "null" ] }, + "pluginId": { + "type": [ + "string", + "null" + ] + }, "result": { "anyOf": [ { diff --git a/codex-rs/app-server-protocol/schema/json/v2/TurnStartedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/TurnStartedNotification.json index cbde541e52..8c57890a3b 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/TurnStartedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/TurnStartedNotification.json @@ -944,6 +944,12 @@ "null" ] }, + "pluginId": { + "type": [ + "string", + "null" + ] + }, "result": { "anyOf": [ { diff --git a/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts b/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts index 14be7db47a..86ba2cd171 100644 --- a/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts +++ b/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts @@ -62,6 +62,9 @@ import type { ThreadApproveGuardianDeniedActionParams } from "./v2/ThreadApprove import type { ThreadArchiveParams } from "./v2/ThreadArchiveParams"; import type { ThreadCompactStartParams } from "./v2/ThreadCompactStartParams"; import type { ThreadForkParams } from "./v2/ThreadForkParams"; +import type { ThreadGoalClearParams } from "./v2/ThreadGoalClearParams"; +import type { ThreadGoalGetParams } from "./v2/ThreadGoalGetParams"; +import type { ThreadGoalSetParams } from "./v2/ThreadGoalSetParams"; import type { ThreadInjectItemsParams } from "./v2/ThreadInjectItemsParams"; import type { ThreadListParams } from "./v2/ThreadListParams"; import type { ThreadLoadedListParams } from "./v2/ThreadLoadedListParams"; @@ -82,4 +85,4 @@ import type { WindowsSandboxSetupStartParams } from "./v2/WindowsSandboxSetupSta /** * Request from the client to the server. */ -export type ClientRequest ={ "method": "initialize", id: RequestId, params: InitializeParams, } | { "method": "thread/start", id: RequestId, params: ThreadStartParams, } | { "method": "thread/resume", id: RequestId, params: ThreadResumeParams, } | { "method": "thread/fork", id: RequestId, params: ThreadForkParams, } | { "method": "thread/archive", id: RequestId, params: ThreadArchiveParams, } | { "method": "thread/unsubscribe", id: RequestId, params: ThreadUnsubscribeParams, } | { "method": "thread/name/set", id: RequestId, params: ThreadSetNameParams, } | { "method": "thread/metadata/update", id: RequestId, params: ThreadMetadataUpdateParams, } | { "method": "thread/unarchive", id: RequestId, params: ThreadUnarchiveParams, } | { "method": "thread/compact/start", id: RequestId, params: ThreadCompactStartParams, } | { "method": "thread/shellCommand", id: RequestId, params: ThreadShellCommandParams, } | { "method": "thread/approveGuardianDeniedAction", id: RequestId, params: ThreadApproveGuardianDeniedActionParams, } | { "method": "thread/rollback", id: RequestId, params: ThreadRollbackParams, } | { "method": "thread/list", id: RequestId, params: ThreadListParams, } | { "method": "thread/loaded/list", id: RequestId, params: ThreadLoadedListParams, } | { "method": "thread/read", id: RequestId, params: ThreadReadParams, } | { "method": "thread/inject_items", id: RequestId, params: ThreadInjectItemsParams, } | { "method": "skills/list", id: RequestId, params: SkillsListParams, } | { "method": "hooks/list", id: RequestId, params: HooksListParams, } | { "method": "marketplace/add", id: RequestId, params: MarketplaceAddParams, } | { "method": "marketplace/remove", id: RequestId, params: MarketplaceRemoveParams, } | { "method": "marketplace/upgrade", id: RequestId, params: MarketplaceUpgradeParams, } | { "method": "plugin/list", id: RequestId, params: PluginListParams, } | { "method": "plugin/installed", id: RequestId, params: PluginInstalledParams, } | { "method": "plugin/read", id: RequestId, params: PluginReadParams, } | { "method": "plugin/skill/read", id: RequestId, params: PluginSkillReadParams, } | { "method": "plugin/share/save", id: RequestId, params: PluginShareSaveParams, } | { "method": "plugin/share/updateTargets", id: RequestId, params: PluginShareUpdateTargetsParams, } | { "method": "plugin/share/list", id: RequestId, params: PluginShareListParams, } | { "method": "plugin/share/checkout", id: RequestId, params: PluginShareCheckoutParams, } | { "method": "plugin/share/delete", id: RequestId, params: PluginShareDeleteParams, } | { "method": "app/list", id: RequestId, params: AppsListParams, } | { "method": "fs/readFile", id: RequestId, params: FsReadFileParams, } | { "method": "fs/writeFile", id: RequestId, params: FsWriteFileParams, } | { "method": "fs/createDirectory", id: RequestId, params: FsCreateDirectoryParams, } | { "method": "fs/getMetadata", id: RequestId, params: FsGetMetadataParams, } | { "method": "fs/readDirectory", id: RequestId, params: FsReadDirectoryParams, } | { "method": "fs/remove", id: RequestId, params: FsRemoveParams, } | { "method": "fs/copy", id: RequestId, params: FsCopyParams, } | { "method": "fs/watch", id: RequestId, params: FsWatchParams, } | { "method": "fs/unwatch", id: RequestId, params: FsUnwatchParams, } | { "method": "skills/config/write", id: RequestId, params: SkillsConfigWriteParams, } | { "method": "plugin/install", id: RequestId, params: PluginInstallParams, } | { "method": "plugin/uninstall", id: RequestId, params: PluginUninstallParams, } | { "method": "turn/start", id: RequestId, params: TurnStartParams, } | { "method": "turn/steer", id: RequestId, params: TurnSteerParams, } | { "method": "turn/interrupt", id: RequestId, params: TurnInterruptParams, } | { "method": "review/start", id: RequestId, params: ReviewStartParams, } | { "method": "model/list", id: RequestId, params: ModelListParams, } | { "method": "modelProvider/capabilities/read", id: RequestId, params: ModelProviderCapabilitiesReadParams, } | { "method": "experimentalFeature/list", id: RequestId, params: ExperimentalFeatureListParams, } | { "method": "permissionProfile/list", id: RequestId, params: PermissionProfileListParams, } | { "method": "experimentalFeature/enablement/set", id: RequestId, params: ExperimentalFeatureEnablementSetParams, } | { "method": "mcpServer/oauth/login", id: RequestId, params: McpServerOauthLoginParams, } | { "method": "config/mcpServer/reload", id: RequestId, params: undefined, } | { "method": "mcpServerStatus/list", id: RequestId, params: ListMcpServerStatusParams, } | { "method": "mcpServer/resource/read", id: RequestId, params: McpResourceReadParams, } | { "method": "mcpServer/tool/call", id: RequestId, params: McpServerToolCallParams, } | { "method": "windowsSandbox/setupStart", id: RequestId, params: WindowsSandboxSetupStartParams, } | { "method": "windowsSandbox/readiness", id: RequestId, params: undefined, } | { "method": "account/login/start", id: RequestId, params: LoginAccountParams, } | { "method": "account/login/cancel", id: RequestId, params: CancelLoginAccountParams, } | { "method": "account/logout", id: RequestId, params: undefined, } | { "method": "account/rateLimits/read", id: RequestId, params: undefined, } | { "method": "account/sendAddCreditsNudgeEmail", id: RequestId, params: SendAddCreditsNudgeEmailParams, } | { "method": "feedback/upload", id: RequestId, params: FeedbackUploadParams, } | { "method": "command/exec", id: RequestId, params: CommandExecParams, } | { "method": "command/exec/write", id: RequestId, params: CommandExecWriteParams, } | { "method": "command/exec/terminate", id: RequestId, params: CommandExecTerminateParams, } | { "method": "command/exec/resize", id: RequestId, params: CommandExecResizeParams, } | { "method": "config/read", id: RequestId, params: ConfigReadParams, } | { "method": "externalAgentConfig/detect", id: RequestId, params: ExternalAgentConfigDetectParams, } | { "method": "externalAgentConfig/import", id: RequestId, params: ExternalAgentConfigImportParams, } | { "method": "config/value/write", id: RequestId, params: ConfigValueWriteParams, } | { "method": "config/batchWrite", id: RequestId, params: ConfigBatchWriteParams, } | { "method": "configRequirements/read", id: RequestId, params: undefined, } | { "method": "account/read", id: RequestId, params: GetAccountParams, } | { "method": "getConversationSummary", id: RequestId, params: GetConversationSummaryParams, } | { "method": "gitDiffToRemote", id: RequestId, params: GitDiffToRemoteParams, } | { "method": "getAuthStatus", id: RequestId, params: GetAuthStatusParams, } | { "method": "fuzzyFileSearch", id: RequestId, params: FuzzyFileSearchParams, }; +export type ClientRequest ={ "method": "initialize", id: RequestId, params: InitializeParams, } | { "method": "thread/start", id: RequestId, params: ThreadStartParams, } | { "method": "thread/resume", id: RequestId, params: ThreadResumeParams, } | { "method": "thread/fork", id: RequestId, params: ThreadForkParams, } | { "method": "thread/archive", id: RequestId, params: ThreadArchiveParams, } | { "method": "thread/unsubscribe", id: RequestId, params: ThreadUnsubscribeParams, } | { "method": "thread/name/set", id: RequestId, params: ThreadSetNameParams, } | { "method": "thread/goal/set", id: RequestId, params: ThreadGoalSetParams, } | { "method": "thread/goal/get", id: RequestId, params: ThreadGoalGetParams, } | { "method": "thread/goal/clear", id: RequestId, params: ThreadGoalClearParams, } | { "method": "thread/metadata/update", id: RequestId, params: ThreadMetadataUpdateParams, } | { "method": "thread/unarchive", id: RequestId, params: ThreadUnarchiveParams, } | { "method": "thread/compact/start", id: RequestId, params: ThreadCompactStartParams, } | { "method": "thread/shellCommand", id: RequestId, params: ThreadShellCommandParams, } | { "method": "thread/approveGuardianDeniedAction", id: RequestId, params: ThreadApproveGuardianDeniedActionParams, } | { "method": "thread/rollback", id: RequestId, params: ThreadRollbackParams, } | { "method": "thread/list", id: RequestId, params: ThreadListParams, } | { "method": "thread/loaded/list", id: RequestId, params: ThreadLoadedListParams, } | { "method": "thread/read", id: RequestId, params: ThreadReadParams, } | { "method": "thread/inject_items", id: RequestId, params: ThreadInjectItemsParams, } | { "method": "skills/list", id: RequestId, params: SkillsListParams, } | { "method": "hooks/list", id: RequestId, params: HooksListParams, } | { "method": "marketplace/add", id: RequestId, params: MarketplaceAddParams, } | { "method": "marketplace/remove", id: RequestId, params: MarketplaceRemoveParams, } | { "method": "marketplace/upgrade", id: RequestId, params: MarketplaceUpgradeParams, } | { "method": "plugin/list", id: RequestId, params: PluginListParams, } | { "method": "plugin/installed", id: RequestId, params: PluginInstalledParams, } | { "method": "plugin/read", id: RequestId, params: PluginReadParams, } | { "method": "plugin/skill/read", id: RequestId, params: PluginSkillReadParams, } | { "method": "plugin/share/save", id: RequestId, params: PluginShareSaveParams, } | { "method": "plugin/share/updateTargets", id: RequestId, params: PluginShareUpdateTargetsParams, } | { "method": "plugin/share/list", id: RequestId, params: PluginShareListParams, } | { "method": "plugin/share/checkout", id: RequestId, params: PluginShareCheckoutParams, } | { "method": "plugin/share/delete", id: RequestId, params: PluginShareDeleteParams, } | { "method": "app/list", id: RequestId, params: AppsListParams, } | { "method": "fs/readFile", id: RequestId, params: FsReadFileParams, } | { "method": "fs/writeFile", id: RequestId, params: FsWriteFileParams, } | { "method": "fs/createDirectory", id: RequestId, params: FsCreateDirectoryParams, } | { "method": "fs/getMetadata", id: RequestId, params: FsGetMetadataParams, } | { "method": "fs/readDirectory", id: RequestId, params: FsReadDirectoryParams, } | { "method": "fs/remove", id: RequestId, params: FsRemoveParams, } | { "method": "fs/copy", id: RequestId, params: FsCopyParams, } | { "method": "fs/watch", id: RequestId, params: FsWatchParams, } | { "method": "fs/unwatch", id: RequestId, params: FsUnwatchParams, } | { "method": "skills/config/write", id: RequestId, params: SkillsConfigWriteParams, } | { "method": "plugin/install", id: RequestId, params: PluginInstallParams, } | { "method": "plugin/uninstall", id: RequestId, params: PluginUninstallParams, } | { "method": "turn/start", id: RequestId, params: TurnStartParams, } | { "method": "turn/steer", id: RequestId, params: TurnSteerParams, } | { "method": "turn/interrupt", id: RequestId, params: TurnInterruptParams, } | { "method": "review/start", id: RequestId, params: ReviewStartParams, } | { "method": "model/list", id: RequestId, params: ModelListParams, } | { "method": "modelProvider/capabilities/read", id: RequestId, params: ModelProviderCapabilitiesReadParams, } | { "method": "experimentalFeature/list", id: RequestId, params: ExperimentalFeatureListParams, } | { "method": "permissionProfile/list", id: RequestId, params: PermissionProfileListParams, } | { "method": "experimentalFeature/enablement/set", id: RequestId, params: ExperimentalFeatureEnablementSetParams, } | { "method": "mcpServer/oauth/login", id: RequestId, params: McpServerOauthLoginParams, } | { "method": "config/mcpServer/reload", id: RequestId, params: undefined, } | { "method": "mcpServerStatus/list", id: RequestId, params: ListMcpServerStatusParams, } | { "method": "mcpServer/resource/read", id: RequestId, params: McpResourceReadParams, } | { "method": "mcpServer/tool/call", id: RequestId, params: McpServerToolCallParams, } | { "method": "windowsSandbox/setupStart", id: RequestId, params: WindowsSandboxSetupStartParams, } | { "method": "windowsSandbox/readiness", id: RequestId, params: undefined, } | { "method": "account/login/start", id: RequestId, params: LoginAccountParams, } | { "method": "account/login/cancel", id: RequestId, params: CancelLoginAccountParams, } | { "method": "account/logout", id: RequestId, params: undefined, } | { "method": "account/rateLimits/read", id: RequestId, params: undefined, } | { "method": "account/sendAddCreditsNudgeEmail", id: RequestId, params: SendAddCreditsNudgeEmailParams, } | { "method": "feedback/upload", id: RequestId, params: FeedbackUploadParams, } | { "method": "command/exec", id: RequestId, params: CommandExecParams, } | { "method": "command/exec/write", id: RequestId, params: CommandExecWriteParams, } | { "method": "command/exec/terminate", id: RequestId, params: CommandExecTerminateParams, } | { "method": "command/exec/resize", id: RequestId, params: CommandExecResizeParams, } | { "method": "config/read", id: RequestId, params: ConfigReadParams, } | { "method": "externalAgentConfig/detect", id: RequestId, params: ExternalAgentConfigDetectParams, } | { "method": "externalAgentConfig/import", id: RequestId, params: ExternalAgentConfigImportParams, } | { "method": "config/value/write", id: RequestId, params: ConfigValueWriteParams, } | { "method": "config/batchWrite", id: RequestId, params: ConfigBatchWriteParams, } | { "method": "configRequirements/read", id: RequestId, params: undefined, } | { "method": "account/read", id: RequestId, params: GetAccountParams, } | { "method": "getConversationSummary", id: RequestId, params: GetConversationSummaryParams, } | { "method": "gitDiffToRemote", id: RequestId, params: GitDiffToRemoteParams, } | { "method": "getAuthStatus", id: RequestId, params: GetAuthStatusParams, } | { "method": "fuzzyFileSearch", id: RequestId, params: FuzzyFileSearchParams, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/HookEventName.ts b/codex-rs/app-server-protocol/schema/typescript/v2/HookEventName.ts index b12f47169f..477476289d 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/HookEventName.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/HookEventName.ts @@ -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 HookEventName = "preToolUse" | "permissionRequest" | "postToolUse" | "preCompact" | "postCompact" | "sessionStart" | "userPromptSubmit" | "subagentStart" | "stop"; +export type HookEventName = "preToolUse" | "permissionRequest" | "postToolUse" | "preCompact" | "postCompact" | "sessionStart" | "userPromptSubmit" | "subagentStart" | "subagentStop" | "stop"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ManagedHooksRequirements.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ManagedHooksRequirements.ts index 2b54af3c6d..1143bd017f 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ManagedHooksRequirements.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ManagedHooksRequirements.ts @@ -3,4 +3,4 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { ConfiguredHookMatcherGroup } from "./ConfiguredHookMatcherGroup"; -export type ManagedHooksRequirements = { managedDir: string | null, windowsManagedDir: string | null, PreToolUse: Array, PermissionRequest: Array, PostToolUse: Array, PreCompact: Array, PostCompact: Array, SessionStart: Array, UserPromptSubmit: Array, SubagentStart: Array, Stop: Array, }; +export type ManagedHooksRequirements = { managedDir: string | null, windowsManagedDir: string | null, PreToolUse: Array, PermissionRequest: Array, PostToolUse: Array, PreCompact: Array, PostCompact: Array, SessionStart: Array, UserPromptSubmit: Array, SubagentStart: Array, SubagentStop: Array, Stop: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/Model.ts b/codex-rs/app-server-protocol/schema/typescript/v2/Model.ts index 2354ffbf9e..e9dbf15b0b 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/Model.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/Model.ts @@ -12,4 +12,8 @@ export type Model = { id: string, model: string, upgrade: string | null, upgrade /** * Deprecated: use `serviceTiers` instead. */ -additionalSpeedTiers: Array, serviceTiers: Array, isDefault: boolean, }; +additionalSpeedTiers: Array, serviceTiers: Array, +/** + * Catalog default service tier id for this model, when one is configured. + */ +defaultServiceTier: string | null, isDefault: boolean, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadGoalClearParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadGoalClearParams.ts new file mode 100644 index 0000000000..efefc2538a --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadGoalClearParams.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type ThreadGoalClearParams = { threadId: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadGoalClearResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadGoalClearResponse.ts new file mode 100644 index 0000000000..882176df74 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadGoalClearResponse.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type ThreadGoalClearResponse = { cleared: boolean, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadGoalGetParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadGoalGetParams.ts new file mode 100644 index 0000000000..59f0006c87 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadGoalGetParams.ts @@ -0,0 +1,5 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type ThreadGoalGetParams = { threadId: string, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadGoalGetResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadGoalGetResponse.ts new file mode 100644 index 0000000000..fa2b6089d4 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadGoalGetResponse.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ThreadGoal } from "./ThreadGoal"; + +export type ThreadGoalGetResponse = { goal: ThreadGoal | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadGoalSetParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadGoalSetParams.ts new file mode 100644 index 0000000000..b92720c178 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadGoalSetParams.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ThreadGoalStatus } from "./ThreadGoalStatus"; + +export type ThreadGoalSetParams = { threadId: string, objective?: string | null, status?: ThreadGoalStatus | null, tokenBudget?: number | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadGoalSetResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadGoalSetResponse.ts new file mode 100644 index 0000000000..0f57130ce0 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadGoalSetResponse.ts @@ -0,0 +1,6 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { ThreadGoal } from "./ThreadGoal"; + +export type ThreadGoalSetResponse = { goal: ThreadGoal, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadItem.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadItem.ts index f7880c9d32..1b655b460e 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ThreadItem.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ThreadItem.ts @@ -53,7 +53,7 @@ exitCode: number | null, /** * The duration of the command execution in milliseconds. */ -durationMs: number | null, } | { "type": "fileChange", id: string, changes: Array, status: PatchApplyStatus, } | { "type": "mcpToolCall", id: string, server: string, tool: string, status: McpToolCallStatus, arguments: JsonValue, mcpAppResourceUri?: string, result: McpToolCallResult | null, error: McpToolCallError | null, +durationMs: number | null, } | { "type": "fileChange", id: string, changes: Array, status: PatchApplyStatus, } | { "type": "mcpToolCall", id: string, server: string, tool: string, status: McpToolCallStatus, arguments: JsonValue, mcpAppResourceUri?: string, pluginId: string | null, result: McpToolCallResult | null, error: McpToolCallError | null, /** * The duration of the MCP tool call in milliseconds. */ diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts index 4e9080ccdf..e9b8993c26 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts @@ -365,7 +365,13 @@ export type { ThreadCompactStartResponse } from "./ThreadCompactStartResponse"; export type { ThreadForkParams } from "./ThreadForkParams"; export type { ThreadForkResponse } from "./ThreadForkResponse"; export type { ThreadGoal } from "./ThreadGoal"; +export type { ThreadGoalClearParams } from "./ThreadGoalClearParams"; +export type { ThreadGoalClearResponse } from "./ThreadGoalClearResponse"; export type { ThreadGoalClearedNotification } from "./ThreadGoalClearedNotification"; +export type { ThreadGoalGetParams } from "./ThreadGoalGetParams"; +export type { ThreadGoalGetResponse } from "./ThreadGoalGetResponse"; +export type { ThreadGoalSetParams } from "./ThreadGoalSetParams"; +export type { ThreadGoalSetResponse } from "./ThreadGoalSetResponse"; export type { ThreadGoalStatus } from "./ThreadGoalStatus"; export type { ThreadGoalUpdatedNotification } from "./ThreadGoalUpdatedNotification"; export type { ThreadInjectItemsParams } from "./ThreadInjectItemsParams"; diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index 1533449138..76334e8a6a 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -494,19 +494,16 @@ client_request_definitions! { serialization: thread_id(params.thread_id), response: v2::ThreadSetNameResponse, }, - #[experimental("thread/goal/set")] ThreadGoalSet => "thread/goal/set" { params: v2::ThreadGoalSetParams, serialization: thread_id(params.thread_id), response: v2::ThreadGoalSetResponse, }, - #[experimental("thread/goal/get")] ThreadGoalGet => "thread/goal/get" { params: v2::ThreadGoalGetParams, serialization: thread_id(params.thread_id), response: v2::ThreadGoalGetResponse, }, - #[experimental("thread/goal/clear")] ThreadGoalClear => "thread/goal/clear" { params: v2::ThreadGoalClearParams, serialization: thread_id(params.thread_id), @@ -1473,9 +1470,7 @@ server_notification_definitions! { ThreadClosed => "thread/closed" (v2::ThreadClosedNotification), SkillsChanged => "skills/changed" (v2::SkillsChangedNotification), ThreadNameUpdated => "thread/name/updated" (v2::ThreadNameUpdatedNotification), - #[experimental("thread/goal/updated")] ThreadGoalUpdated => "thread/goal/updated" (v2::ThreadGoalUpdatedNotification), - #[experimental("thread/goal/cleared")] ThreadGoalCleared => "thread/goal/cleared" (v2::ThreadGoalClearedNotification), #[experimental("thread/settings/updated")] ThreadSettingsUpdated => "thread/settings/updated" (v2::ThreadSettingsUpdatedNotification), @@ -3035,7 +3030,7 @@ mod tests { } #[test] - fn thread_goal_methods_are_marked_experimental() { + fn thread_goal_methods_are_not_marked_experimental() { let set_request = ClientRequest::ThreadGoalSet { request_id: RequestId::Integer(1), params: v2::ThreadGoalSetParams { @@ -3060,20 +3055,20 @@ mod tests { assert_eq!( crate::experimental_api::ExperimentalApi::experimental_reason(&set_request), - Some("thread/goal/set") + None ); assert_eq!( crate::experimental_api::ExperimentalApi::experimental_reason(&get_request), - Some("thread/goal/get") + None ); assert_eq!( crate::experimental_api::ExperimentalApi::experimental_reason(&clear_request), - Some("thread/goal/clear") + None ); } #[test] - fn thread_goal_notifications_are_marked_experimental() { + fn thread_goal_notifications_are_not_marked_experimental() { let goal = v2::ThreadGoal { thread_id: "thr_123".to_string(), objective: "ship goal mode".to_string(), @@ -3095,11 +3090,11 @@ mod tests { assert_eq!( crate::experimental_api::ExperimentalApi::experimental_reason(&updated), - Some("thread/goal/updated") + None ); assert_eq!( crate::experimental_api::ExperimentalApi::experimental_reason(&cleared), - Some("thread/goal/cleared") + None ); } diff --git a/codex-rs/app-server-protocol/src/protocol/thread_history.rs b/codex-rs/app-server-protocol/src/protocol/thread_history.rs index 3918e4a9bd..0fbb93f397 100644 --- a/codex-rs/app-server-protocol/src/protocol/thread_history.rs +++ b/codex-rs/app-server-protocol/src/protocol/thread_history.rs @@ -525,6 +525,7 @@ impl ThreadHistoryBuilder { .clone() .unwrap_or(serde_json::Value::Null), mcp_app_resource_uri: payload.mcp_app_resource_uri.clone(), + plugin_id: payload.plugin_id.clone(), result: None, error: None, duration_ms: None, @@ -566,6 +567,7 @@ impl ThreadHistoryBuilder { .clone() .unwrap_or(serde_json::Value::Null), mcp_app_resource_uri: payload.mcp_app_resource_uri.clone(), + plugin_id: payload.plugin_id.clone(), result, error, duration_ms, @@ -1911,6 +1913,7 @@ mod tests { arguments: Some(serde_json::json!({"id":"123"})), }, mcp_app_resource_uri: None, + plugin_id: None, duration: Duration::from_millis(8), result: Err("boom".into()), }), @@ -1960,6 +1963,7 @@ mod tests { status: McpToolCallStatus::Failed, arguments: serde_json::json!({"id":"123"}), mcp_app_resource_uri: None, + plugin_id: None, result: None, error: Some(McpToolCallError { message: "boom".into(), @@ -1986,6 +1990,7 @@ mod tests { arguments: Some(serde_json::json!({"id":"123"})), }, mcp_app_resource_uri: Some("ui://widget/lookup.html".into()), + plugin_id: Some("sample@test".into()), duration: Duration::from_millis(8), result: Ok(CallToolResult { content: vec![serde_json::json!({ @@ -2016,6 +2021,7 @@ mod tests { status: McpToolCallStatus::Completed, arguments: serde_json::json!({"id":"123"}), mcp_app_resource_uri: Some("ui://widget/lookup.html".into()), + plugin_id: Some("sample@test".into()), result: Some(Box::new(McpToolCallResult { content: vec![serde_json::json!({ "type": "text", diff --git a/codex-rs/app-server-protocol/src/protocol/v2/config.rs b/codex-rs/app-server-protocol/src/protocol/v2/config.rs index 25d75b56b4..98466078e2 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/config.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/config.rs @@ -434,6 +434,9 @@ pub struct ManagedHooksRequirements { #[serde(rename = "SubagentStart")] #[ts(rename = "SubagentStart")] pub subagent_start: Vec, + #[serde(rename = "SubagentStop")] + #[ts(rename = "SubagentStop")] + pub subagent_stop: Vec, #[serde(rename = "Stop")] #[ts(rename = "Stop")] pub stop: Vec, diff --git a/codex-rs/app-server-protocol/src/protocol/v2/hook.rs b/codex-rs/app-server-protocol/src/protocol/v2/hook.rs index 8163e9f51a..6e6c1ef7d4 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/hook.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/hook.rs @@ -17,7 +17,7 @@ use ts_rs::TS; v2_enum_from_core!( pub enum HookEventName from CoreHookEventName { - PreToolUse, PermissionRequest, PostToolUse, PreCompact, PostCompact, SessionStart, UserPromptSubmit, SubagentStart, Stop + PreToolUse, PermissionRequest, PostToolUse, PreCompact, PostCompact, SessionStart, UserPromptSubmit, SubagentStart, SubagentStop, Stop } ); diff --git a/codex-rs/app-server-protocol/src/protocol/v2/item.rs b/codex-rs/app-server-protocol/src/protocol/v2/item.rs index 0e22c48590..39e489d6aa 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/item.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/item.rs @@ -286,6 +286,7 @@ pub enum ThreadItem { #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] mcp_app_resource_uri: Option, + plugin_id: Option, result: Option>, error: Option, /// The duration of the MCP tool call in milliseconds. @@ -846,6 +847,7 @@ impl From for ThreadItem { status: McpToolCallStatus::from(mcp.status), arguments: mcp.arguments, mcp_app_resource_uri: mcp.mcp_app_resource_uri, + plugin_id: mcp.plugin_id, result: mcp.result.map(McpToolCallResult::from).map(Box::new), error: mcp.error.map(McpToolCallError::from), duration_ms, diff --git a/codex-rs/app-server-protocol/src/protocol/v2/model.rs b/codex-rs/app-server-protocol/src/protocol/v2/model.rs index cd139e9c4b..7f97d791a6 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/model.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/model.rs @@ -98,6 +98,9 @@ pub struct Model { pub additional_speed_tiers: Vec, #[serde(default)] pub service_tiers: Vec, + /// Catalog default service tier id for this model, when one is configured. + #[serde(default)] + pub default_service_tier: Option, // Only one model should be marked as default. pub is_default: bool, } diff --git a/codex-rs/app-server-protocol/src/protocol/v2/tests.rs b/codex-rs/app-server-protocol/src/protocol/v2/tests.rs index a7cec1d36d..3aadc6b24c 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/tests.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/tests.rs @@ -2491,6 +2491,7 @@ fn core_turn_item_into_thread_item_converts_supported_variants() { tool: "tool".to_string(), arguments: json!({"arg": "value"}), mcp_app_resource_uri: Some("app://connector".to_string()), + plugin_id: Some("sample@test".to_string()), status: CoreMcpToolCallStatus::InProgress, result: None, error: None, @@ -2506,6 +2507,7 @@ fn core_turn_item_into_thread_item_converts_supported_variants() { status: McpToolCallStatus::InProgress, arguments: json!({"arg": "value"}), mcp_app_resource_uri: Some("app://connector".to_string()), + plugin_id: Some("sample@test".to_string()), result: None, error: None, duration_ms: None, @@ -2518,6 +2520,7 @@ fn core_turn_item_into_thread_item_converts_supported_variants() { tool: "tool".to_string(), arguments: JsonValue::Null, mcp_app_resource_uri: None, + plugin_id: None, status: CoreMcpToolCallStatus::Completed, result: Some(CallToolResult { content: vec![json!({"type": "text", "text": "ok"})], @@ -2538,6 +2541,7 @@ fn core_turn_item_into_thread_item_converts_supported_variants() { status: McpToolCallStatus::Completed, arguments: JsonValue::Null, mcp_app_resource_uri: None, + plugin_id: None, result: Some(Box::new(McpToolCallResult { content: vec![json!({"type": "text", "text": "ok"})], structured_content: Some(json!({"ok": true})), diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index 8ce55410a1..29ac2b2cc5 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -188,7 +188,7 @@ Example with notification opt-out: - `fs/watch` — subscribe this connection to filesystem change notifications for an absolute file or directory path and caller-provided `watchId`; returns the canonicalized `path`. - `fs/unwatch` — stop sending notifications for a prior `fs/watch`; returns `{}`. - `fs/changed` — notification emitted when watched paths change, including the `watchId` and `changedPaths`. -- `model/list` — list available models (set `includeHidden: true` to include entries with `hidden: true`), with reasoning effort options, `additionalSpeedTiers`, optional legacy `upgrade` model ids, optional `upgradeInfo` metadata (`model`, `upgradeCopy`, `modelLink`, `migrationMarkdown`), and optional `availabilityNux` metadata. +- `model/list` — list available models (set `includeHidden: true` to include entries with `hidden: true`), with reasoning effort options, `additionalSpeedTiers`, `serviceTiers`, optional `defaultServiceTier`, optional legacy `upgrade` model ids, optional `upgradeInfo` metadata (`model`, `upgradeCopy`, `modelLink`, `migrationMarkdown`), and optional `availabilityNux` metadata. - `modelProvider/capabilities/read` — read provider-level capabilities for the currently configured model provider. - `experimentalFeature/list` — list feature flags with stage metadata (`beta`, `underDevelopment`, `stable`, etc.), enabled/default-enabled state, and cursor pagination. Pass `threadId` when showing feature state for an existing loaded thread so `enabled` is computed from that thread's refreshed config, including project-local config for the thread's cwd; if omitted, the server uses its default config resolution context. For non-beta flags, `displayName`/`description`/`announcement` are `null`. - `permissionProfile/list` — beta; list available permission profile ids with optional display `description` text, using cursor pagination. Pass `cwd` when the caller needs project-local `[permissions.]` entries to be included in the current catalog view. @@ -1231,7 +1231,7 @@ Today both notifications carry an empty `items` array even when item events were - `reasoning` — `{id, summary, content}` where `summary` holds streamed reasoning summaries (applicable for most OpenAI models) and `content` holds raw reasoning blocks (applicable for e.g. open source models). - `commandExecution` — `{id, command, cwd, status, commandActions, aggregatedOutput?, exitCode?, durationMs?}` for sandboxed commands; `status` is `inProgress`, `completed`, `failed`, or `declined`. - `fileChange` — `{id, changes, status}` describing proposed edits; `changes` list `{path, kind, diff}` and `status` is `inProgress`, `completed`, `failed`, or `declined`. -- `mcpToolCall` — `{id, server, tool, status, arguments, result?, error?}` describing MCP calls; `status` is `inProgress`, `completed`, or `failed`. +- `mcpToolCall` — `{id, server, tool, status, arguments, mcpAppResourceUri?, pluginId, result?, error?}` describing MCP calls; `status` is `inProgress`, `completed`, or `failed`. - `collabToolCall` — `{id, tool, status, senderThreadId, receiverThreadId?, newThreadId?, prompt?, agentStatus?}` describing collab tool calls (`spawn_agent`, `send_input`, `resume_agent`, `wait`, `close_agent`); `status` is `inProgress`, `completed`, or `failed`. - `webSearch` — `{id, query, action?}` for a web search request issued by the agent; `action` mirrors the Responses API web_search action payload (`search`, `open_page`, `find_in_page`) and may be omitted until completion. - `imageView` — `{id, path}` emitted when the agent invokes the image viewer tool. diff --git a/codex-rs/app-server/src/config/external_agent_config_tests.rs b/codex-rs/app-server/src/config/external_agent_config_tests.rs index 07b09c5a1e..47f93a5f8b 100644 --- a/codex-rs/app-server/src/config/external_agent_config_tests.rs +++ b/codex-rs/app-server/src/config/external_agent_config_tests.rs @@ -696,10 +696,25 @@ async fn import_home_migrates_supported_config_fields_skills_and_agents_md() { "Codex guidance" ); - assert_eq!( - fs::read_to_string(codex_home.join("config.toml")).expect("read config"), - "sandbox_mode = \"workspace-write\"\n\n[shell_environment_policy]\ninherit = \"core\"\n\n[shell_environment_policy.set]\nCI = \"false\"\nFOO = \"bar\"\nMAX_RETRIES = \"3\"\nMY_TEAM = \"codex\"\n" - ); + let config: TomlValue = + toml::from_str(&fs::read_to_string(codex_home.join("config.toml")).expect("read config")) + .expect("parse config"); + let expected: TomlValue = toml::from_str( + r#" +sandbox_mode = "workspace-write" + +[shell_environment_policy] +inherit = "core" + +[shell_environment_policy.set] +CI = "false" +FOO = "bar" +MAX_RETRIES = "3" +MY_TEAM = "codex" +"#, + ) + .expect("parse expected config"); + assert_eq!(config, expected); assert_eq!( fs::read_to_string(agents_skills.join("skill-a").join("SKILL.md")) .expect("read copied skill"), @@ -732,10 +747,24 @@ async fn import_home_config_uses_local_settings_over_project_settings() { .await .expect("import"); - assert_eq!( - fs::read_to_string(codex_home.join("config.toml")).expect("read config"), - "sandbox_mode = \"workspace-write\"\n\n[shell_environment_policy]\ninherit = \"core\"\n\n[shell_environment_policy.set]\nFOO = \"local\"\nLOCAL_ONLY = \"true\"\nPROJECT_ONLY = \"yes\"\n" - ); + let config: TomlValue = + toml::from_str(&fs::read_to_string(codex_home.join("config.toml")).expect("read config")) + .expect("parse config"); + let expected: TomlValue = toml::from_str( + r#" +sandbox_mode = "workspace-write" + +[shell_environment_policy] +inherit = "core" + +[shell_environment_policy.set] +FOO = "local" +LOCAL_ONLY = "true" +PROJECT_ONLY = "yes" +"#, + ) + .expect("parse expected config"); + assert_eq!(config, expected); } #[tokio::test] diff --git a/codex-rs/app-server/src/models.rs b/codex-rs/app-server/src/models.rs index 4d75a20580..e53f13df84 100644 --- a/codex-rs/app-server/src/models.rs +++ b/codex-rs/app-server/src/models.rs @@ -53,6 +53,7 @@ fn model_from_preset(preset: ModelPreset) -> Model { description: service_tier.description, }) .collect(), + default_service_tier: preset.default_service_tier, is_default: preset.is_default, } } diff --git a/codex-rs/app-server/src/request_processors/config_processor.rs b/codex-rs/app-server/src/request_processors/config_processor.rs index 860385a1ff..5327f4ffa2 100644 --- a/codex-rs/app-server/src/request_processors/config_processor.rs +++ b/codex-rs/app-server/src/request_processors/config_processor.rs @@ -467,6 +467,7 @@ fn map_hooks_requirements_to_api(hooks: ManagedHooksRequirementsToml) -> Managed session_start, user_prompt_submit, subagent_start, + subagent_stop, stop, } = hooks; @@ -481,6 +482,7 @@ fn map_hooks_requirements_to_api(hooks: ManagedHooksRequirementsToml) -> Managed session_start: map_hook_matcher_groups_to_api(session_start), user_prompt_submit: map_hook_matcher_groups_to_api(user_prompt_submit), subagent_start: map_hook_matcher_groups_to_api(subagent_start), + subagent_stop: map_hook_matcher_groups_to_api(subagent_stop), stop: map_hook_matcher_groups_to_api(stop), } } diff --git a/codex-rs/app-server/src/request_processors/thread_resume_redaction.rs b/codex-rs/app-server/src/request_processors/thread_resume_redaction.rs index d547aef3f3..b1e8608842 100644 --- a/codex-rs/app-server/src/request_processors/thread_resume_redaction.rs +++ b/codex-rs/app-server/src/request_processors/thread_resume_redaction.rs @@ -79,6 +79,7 @@ mod tests { status: McpToolCallStatus::Completed, arguments: serde_json::json!({"secret":"argument"}), mcp_app_resource_uri: Some("ui://widget/lookup.html".to_string()), + plugin_id: Some("sample@test".to_string()), result: Some(Box::new(McpToolCallResult { content: vec![serde_json::json!({ "type": "text", @@ -120,6 +121,7 @@ mod tests { status: McpToolCallStatus::Completed, arguments: JsonValue::String(REDACTED_PAYLOAD.to_string()), mcp_app_resource_uri: Some("ui://widget/lookup.html".to_string()), + plugin_id: Some("sample@test".to_string()), result: Some(Box::new(redacted_mcp_tool_call_result())), error: None, duration_ms: Some(8), @@ -136,6 +138,7 @@ mod tests { status: McpToolCallStatus::Failed, arguments: serde_json::json!({"secret":"argument"}), mcp_app_resource_uri: None, + plugin_id: None, result: None, error: Some(McpToolCallError { message: "secret error".to_string(), @@ -154,6 +157,7 @@ mod tests { status: McpToolCallStatus::Failed, arguments: JsonValue::String(REDACTED_PAYLOAD.to_string()), mcp_app_resource_uri: None, + plugin_id: None, result: None, error: Some(McpToolCallError { message: REDACTED_PAYLOAD.to_string(), diff --git a/codex-rs/app-server/src/transport_tests.rs b/codex-rs/app-server/src/transport_tests.rs index 5790e46a17..57a6c4c454 100644 --- a/codex-rs/app-server/src/transport_tests.rs +++ b/codex-rs/app-server/src/transport_tests.rs @@ -2,9 +2,8 @@ use super::*; use codex_app_server_protocol::ConfigWarningNotification; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ServerNotification; -use codex_app_server_protocol::ThreadGoal; -use codex_app_server_protocol::ThreadGoalStatus; -use codex_app_server_protocol::ThreadGoalUpdatedNotification; +use codex_app_server_protocol::ThreadRealtimeStartedNotification; +use codex_protocol::protocol::RealtimeConversationVersion; use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; use serde_json::json; @@ -15,20 +14,11 @@ fn absolute_path(path: &str) -> AbsolutePathBuf { AbsolutePathBuf::from_absolute_path(path).expect("absolute path") } -fn thread_goal_updated_notification() -> ServerNotification { - ServerNotification::ThreadGoalUpdated(ThreadGoalUpdatedNotification { +fn thread_realtime_started_notification() -> ServerNotification { + ServerNotification::ThreadRealtimeStarted(ThreadRealtimeStartedNotification { thread_id: "thread-1".to_string(), - turn_id: None, - goal: ThreadGoal { - thread_id: "thread-1".to_string(), - objective: "ship goal mode".to_string(), - status: ThreadGoalStatus::Active, - token_budget: None, - tokens_used: 0, - time_used_seconds: 0, - created_at: 1, - updated_at: 1, - }, + realtime_session_id: None, + version: RealtimeConversationVersion::V1, }) } @@ -182,7 +172,7 @@ async fn experimental_notifications_are_dropped_without_capability() { &mut connections, OutgoingEnvelope::ToConnection { connection_id, - message: OutgoingMessage::AppServerNotification(thread_goal_updated_notification()), + message: OutgoingMessage::AppServerNotification(thread_realtime_started_notification()), write_complete_tx: None, }, ) @@ -215,7 +205,7 @@ async fn experimental_notifications_are_preserved_with_capability() { &mut connections, OutgoingEnvelope::ToConnection { connection_id, - message: OutgoingMessage::AppServerNotification(thread_goal_updated_notification()), + message: OutgoingMessage::AppServerNotification(thread_realtime_started_notification()), write_complete_tx: None, }, ) @@ -227,7 +217,7 @@ async fn experimental_notifications_are_preserved_with_capability() { .expect("experimental notification should reach opted-in client"); assert!(matches!( message.message, - OutgoingMessage::AppServerNotification(ServerNotification::ThreadGoalUpdated(_)) + OutgoingMessage::AppServerNotification(ServerNotification::ThreadRealtimeStarted(_)) )); } diff --git a/codex-rs/app-server/tests/common/models_cache.rs b/codex-rs/app-server/tests/common/models_cache.rs index be7d5d047f..0a41daa7c6 100644 --- a/codex-rs/app-server/tests/common/models_cache.rs +++ b/codex-rs/app-server/tests/common/models_cache.rs @@ -30,6 +30,7 @@ fn preset_to_info(preset: &ModelPreset, priority: i32) -> ModelInfo { priority, additional_speed_tiers: preset.additional_speed_tiers.clone(), service_tiers: preset.service_tiers.clone(), + default_service_tier: preset.default_service_tier.clone(), upgrade: preset.upgrade.as_ref().map(Into::into), base_instructions: "base instructions".to_string(), model_messages: None, diff --git a/codex-rs/app-server/tests/suite/v2/mcp_tool.rs b/codex-rs/app-server/tests/suite/v2/mcp_tool.rs index b805f75ba7..46e9b2bf07 100644 --- a/codex-rs/app-server/tests/suite/v2/mcp_tool.rs +++ b/codex-rs/app-server/tests/suite/v2/mcp_tool.rs @@ -513,6 +513,7 @@ url = "{mcp_server_url}/mcp" status, arguments: json!({ "message": LARGE_RESPONSE_MESSAGE }), mcp_app_resource_uri: None, + plugin_id: None, result: Some(result), error: None, duration_ms: None, diff --git a/codex-rs/app-server/tests/suite/v2/model_list.rs b/codex-rs/app-server/tests/suite/v2/model_list.rs index d22bdd2a18..94dcca4377 100644 --- a/codex-rs/app-server/tests/suite/v2/model_list.rs +++ b/codex-rs/app-server/tests/suite/v2/model_list.rs @@ -69,6 +69,7 @@ fn model_from_preset(preset: &ModelPreset) -> Model { description: service_tier.description.clone(), }) .collect(), + default_service_tier: preset.default_service_tier.clone(), is_default: preset.is_default, } } diff --git a/codex-rs/app-server/tests/suite/v2/thread_resume.rs b/codex-rs/app-server/tests/suite/v2/thread_resume.rs index d4baf7d773..f21a973f63 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_resume.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_resume.rs @@ -679,6 +679,7 @@ fn append_resume_redaction_history( arguments: Some(json!({"secret":"argument"})), }, mcp_app_resource_uri: Some("ui://widget/lookup.html".to_string()), + plugin_id: None, duration: Duration::from_millis(8), result: Ok(CallToolResult { content: vec![json!({ diff --git a/codex-rs/app-server/tests/suite/v2/thread_settings_update.rs b/codex-rs/app-server/tests/suite/v2/thread_settings_update.rs index 1bc3d74274..aef2e961c0 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_settings_update.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_settings_update.rs @@ -22,6 +22,7 @@ use codex_app_server_protocol::TurnStartParams; use codex_app_server_protocol::TurnStartResponse; use codex_app_server_protocol::UserInput as V2UserInput; use codex_core::test_support::all_model_presets; +use codex_protocol::config_types::SERVICE_TIER_DEFAULT_REQUEST_VALUE; use core_test_support::responses; use pretty_assertions::assert_eq; use serde_json::Value; @@ -136,7 +137,7 @@ async fn thread_settings_update_while_turn_is_active_emits_notification() -> Res } #[tokio::test] -async fn thread_settings_update_clears_service_tier() -> Result<()> { +async fn thread_settings_update_null_service_tier_uses_default() -> Result<()> { let server = create_mock_responses_server_sequence_unchecked(vec![ create_final_assistant_message_sse_response("done")?, ]) @@ -181,7 +182,10 @@ async fn thread_settings_update_clears_service_tier() -> Result<()> { let clear_updated = read_thread_settings_updated(&mut mcp).await?; assert_eq!(clear_updated.thread_id, thread.id); assert_eq!(clear_updated.thread_settings.model, model_id); - assert_eq!(clear_updated.thread_settings.service_tier, None); + assert_eq!( + clear_updated.thread_settings.service_tier.as_deref(), + Some(SERVICE_TIER_DEFAULT_REQUEST_VALUE) + ); start_text_turn(&mut mcp, thread.id).await?; timeout( diff --git a/codex-rs/app-server/tests/suite/v2/thread_start.rs b/codex-rs/app-server/tests/suite/v2/thread_start.rs index 75c124e893..ecd8ad8e3d 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_start.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_start.rs @@ -28,6 +28,7 @@ use codex_core::config::set_project_trust_level; use codex_exec_server::LOCAL_FS; use codex_git_utils::resolve_root_git_project_for_trust; use codex_login::REFRESH_TOKEN_URL_OVERRIDE_ENV_VAR; +use codex_protocol::config_types::SERVICE_TIER_DEFAULT_REQUEST_VALUE; use codex_protocol::config_types::TrustLevel; use codex_protocol::openai_models::ReasoningEffort; use pretty_assertions::assert_eq; @@ -484,7 +485,7 @@ model_reasoning_effort = "high" } #[tokio::test] -async fn thread_start_accepts_arbitrary_service_tier_id() -> Result<()> { +async fn thread_start_drops_unsupported_service_tier_id() -> Result<()> { let server = create_mock_responses_server_repeating_assistant("Done").await; let codex_home = TempDir::new()?; @@ -508,7 +509,39 @@ async fn thread_start_accepts_arbitrary_service_tier_id() -> Result<()> { .await??; let ThreadStartResponse { service_tier, .. } = to_response::(resp)?; - assert_eq!(service_tier, Some(service_tier_id)); + // Unsupported catalog ids are dropped at session config time instead of echoed back. + assert_eq!(service_tier, None); + Ok(()) +} + +#[tokio::test] +async fn thread_start_accepts_default_service_tier() -> Result<()> { + let server = create_mock_responses_server_repeating_assistant("Done").await; + + let codex_home = TempDir::new()?; + create_config_toml_without_approval_policy(codex_home.path(), &server.uri())?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + + let req_id = mcp + .send_thread_start_request(ThreadStartParams { + service_tier: Some(Some(SERVICE_TIER_DEFAULT_REQUEST_VALUE.to_string())), + ..Default::default() + }) + .await?; + + let resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(req_id)), + ) + .await??; + let ThreadStartResponse { service_tier, .. } = to_response::(resp)?; + + assert_eq!( + service_tier, + Some(SERVICE_TIER_DEFAULT_REQUEST_VALUE.to_string()) + ); Ok(()) } diff --git a/codex-rs/app-server/tests/suite/v2/turn_start.rs b/codex-rs/app-server/tests/suite/v2/turn_start.rs index 66f704f83d..236d57a0ee 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_start.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_start.rs @@ -1004,10 +1004,14 @@ async fn turn_start_rejects_invalid_permission_selection_before_starting_turn() assert!( err.error .message - .contains("invalid thread settings override") + .contains("`approval_policy = \"never\"` cannot be used"), + "unexpected error message: {}", + err.error.message ); assert!( - err.error.message.contains("allowed set [ReadOnly]"), + err.error + .message + .contains("requirements do not allow `sandbox_mode = \"danger-full-access\"`"), "unexpected error message: {}", err.error.message ); diff --git a/codex-rs/cli/src/marketplace_cmd.rs b/codex-rs/cli/src/marketplace_cmd.rs index 2ec948eacb..95dba06f17 100644 --- a/codex-rs/cli/src/marketplace_cmd.rs +++ b/codex-rs/cli/src/marketplace_cmd.rs @@ -6,14 +6,15 @@ use codex_core::config::Config; use codex_core::config::find_codex_home; use codex_core_plugins::PluginMarketplaceUpgradeOutcome; use codex_core_plugins::PluginsManager; -use codex_core_plugins::installed_marketplaces::marketplace_install_root; -use codex_core_plugins::installed_marketplaces::resolve_configured_marketplace_root; +use codex_core_plugins::marketplace::marketplace_root_dir; use codex_core_plugins::marketplace_add::MarketplaceAddRequest; use codex_core_plugins::marketplace_add::add_marketplace; use codex_core_plugins::marketplace_remove::MarketplaceRemoveRequest; use codex_core_plugins::marketplace_remove::remove_marketplace; -use codex_plugin::validate_plugin_segment; use codex_utils_cli::CliConfigOverrides; +use std::collections::HashSet; + +use crate::plugin_cmd::configured_marketplace_snapshot_issues; #[derive(Debug, Parser)] #[command(bin_name = "codex plugin marketplace")] @@ -30,7 +31,7 @@ enum MarketplaceSubcommand { /// Add a local or Git marketplace to the configured marketplace sources. Add(AddMarketplaceArgs), - /// List configured marketplace names and their local snapshot roots. + /// List plugin marketplaces Codex is currently considering and their roots. List, /// Refresh configured Git marketplace snapshots. @@ -150,39 +151,77 @@ async fn run_list(overrides: Vec<(String, toml::Value)>) -> Result<()> { let config = Config::load_with_cli_overrides(overrides) .await .context("failed to load configuration")?; - let configured_marketplaces = config - .config_layer_stack - .get_active_user_layer() - .and_then(|layer| layer.config.get("marketplaces")) - .and_then(toml::Value::as_table); - let Some(configured_marketplaces) = configured_marketplaces else { - println!("No configured plugin marketplaces."); - return Ok(()); - }; - - if configured_marketplaces.is_empty() { - println!("No configured plugin marketplaces."); + let manager = PluginsManager::new(config.codex_home.to_path_buf()); + let plugins_input = config.plugins_config_input(); + let marketplace_listing = manager + .discover_marketplaces_for_config(&plugins_input, &[]) + .context("failed to list plugin marketplaces")?; + let mut load_issues = configured_marketplace_snapshot_issues( + config.codex_home.as_path(), + &plugins_input, + &marketplace_listing.errors, + /*marketplace_name*/ None, + ); + let mut issue_paths = load_issues + .iter() + .map(|issue| issue.path.clone()) + .collect::>(); + for error in &marketplace_listing.errors { + if issue_paths.insert(error.path.to_path_buf()) { + load_issues.push(crate::plugin_cmd::ConfiguredMarketplaceSnapshotIssue { + marketplace_name: error.path.display().to_string(), + path: error.path.to_path_buf(), + message: error.message.clone(), + }); + } + } + if !load_issues.is_empty() { + let issue_lines = load_issues + .iter() + .map(|issue| { + format!( + "- `{}` at {}: {}", + issue.marketplace_name, + issue.path.display(), + issue.message + ) + }) + .collect::>() + .join("\n"); + bail!("failed to load marketplace(s):\n{issue_lines}"); + } + let marketplaces = marketplace_listing.marketplaces; + if marketplaces.is_empty() { + println!("No plugin marketplaces in scope."); return Ok(()); } - let default_install_root = marketplace_install_root(config.codex_home.as_path()); - for (marketplace_name, marketplace) in configured_marketplaces { - if !marketplace.is_table() { - eprintln!("Ignoring invalid marketplace `{marketplace_name}`: expected table."); + let mut seen_roots = HashSet::new(); + let mut rows = Vec::new(); + for marketplace in marketplaces { + let Ok(root) = marketplace_root_dir(&marketplace.path) else { + continue; + }; + if !seen_roots.insert(root.clone()) { continue; } - if let Err(err) = validate_plugin_segment(marketplace_name, "marketplace name") { - eprintln!("Ignoring invalid marketplace `{marketplace_name}`: {err}."); - continue; - } - let root = resolve_configured_marketplace_root( + rows.push((marketplace.name, root)); + } + + let marketplace_width = rows + .iter() + .map(|(name, _)| name.len()) + .max() + .unwrap_or("MARKETPLACE".len()) + .max("MARKETPLACE".len()); + + println!("{:".to_string()); - println!("{marketplace_name}\t{root}"); + root.display() + ); } Ok(()) diff --git a/codex-rs/cli/src/plugin_cmd.rs b/codex-rs/cli/src/plugin_cmd.rs index 593fe644b2..f8c559e506 100644 --- a/codex-rs/cli/src/plugin_cmd.rs +++ b/codex-rs/cli/src/plugin_cmd.rs @@ -5,6 +5,7 @@ use clap::Parser; use codex_core::config::Config; use codex_core::config::find_codex_home; use codex_core_plugins::ConfiguredMarketplace; +use codex_core_plugins::OPENAI_BUNDLED_MARKETPLACE_NAME; use codex_core_plugins::PluginInstallRequest; use codex_core_plugins::PluginsConfigInput; use codex_core_plugins::PluginsManager; @@ -15,10 +16,14 @@ use codex_core_plugins::marketplace::find_marketplace_manifest_path; use codex_plugin::PluginId; use codex_plugin::validate_plugin_segment; use codex_utils_cli::CliConfigOverrides; +use std::path::Path; use std::path::PathBuf; use crate::marketplace_cmd::MarketplaceCli; +const OPENAI_BUNDLED_ALPHA_MARKETPLACE_NAME: &str = "openai-bundled-alpha"; +const OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME: &str = "openai-primary-runtime"; + #[derive(Debug, Parser)] #[command(bin_name = "codex plugin")] pub struct PluginCli { @@ -168,9 +173,13 @@ pub async fn run_plugin_list( println!("No marketplace plugins found."); } } else { - for marketplace in marketplaces { - println!("Marketplace `{}`", marketplace.name); - println!("Path: {}", marketplace.path.as_path().display()); + for (index, marketplace) in marketplaces.into_iter().enumerate() { + let mut rows = Vec::new(); + let mut plugin_width = "PLUGIN".len(); + let mut status_width = "STATUS".len(); + let mut installed_version_width = "VERSION".len(); + let mut path_width = "PATH".len(); + for plugin in &marketplace.plugins { let state = if plugin.installed && plugin.enabled { "installed, enabled" @@ -179,7 +188,51 @@ pub async fn run_plugin_list( } else { "not installed" }; - println!(" {} ({state})", plugin.id); + let installed_version = plugin.installed_version.clone().unwrap_or_default(); + let path = match &plugin.source { + codex_core_plugins::marketplace::MarketplacePluginSource::Local { path } => { + path.as_path().display().to_string() + } + codex_core_plugins::marketplace::MarketplacePluginSource::Git { + url, + path, + ref_name, + sha, + } => { + let mut parts = vec![url.clone()]; + if let Some(path) = path { + parts.push(format!("path `{path}`")); + } + if let Some(ref_name) = ref_name { + parts.push(format!("ref `{ref_name}`")); + } + if let Some(sha) = sha { + parts.push(format!("sha `{sha}`")); + } + parts.join(", ") + } + }; + plugin_width = plugin_width.max(plugin.id.len()); + status_width = status_width.max(state.len()); + installed_version_width = installed_version_width.max(installed_version.len()); + path_width = path_width.max(path.len()); + rows.push((plugin.id.clone(), state, installed_version, path)); + } + + if index > 0 { + println!(); + } + println!("Marketplace `{}`", marketplace.name); + println!("{}", marketplace.path.as_path().display()); + println!(); + println!( + "{:, ) -> Vec { - let Some(user_layer) = plugins_input.config_layer_stack.get_active_user_layer() else { + let Some(user_config) = plugins_input.config_layer_stack.effective_user_config() else { return Vec::new(); }; - let Some(configured_marketplaces) = user_layer - .config + let Some(configured_marketplaces) = user_config .get("marketplaces") .and_then(toml::Value::as_table) else { @@ -367,9 +419,33 @@ fn configured_marketplace_snapshot_issues( if marketplace_name.is_some_and(|name| configured_name != name) { continue; } - if !marketplace.is_table() - || validate_plugin_segment(configured_name, "marketplace name").is_err() + if !marketplace.is_table() { + issues.push(ConfiguredMarketplaceSnapshotIssue { + marketplace_name: configured_name.clone(), + path: PathBuf::from(""), + message: "configured marketplace entry must be a table".to_string(), + }); + continue; + } + if let Err(err) = validate_plugin_segment(configured_name, "marketplace name") { + issues.push(ConfiguredMarketplaceSnapshotIssue { + marketplace_name: configured_name.clone(), + path: PathBuf::from(""), + message: err.to_string(), + }); + continue; + } + if marketplace.get("source_type").and_then(toml::Value::as_str) == Some("local") + && marketplace + .get("source") + .and_then(toml::Value::as_str) + .is_none_or(str::is_empty) { + issues.push(ConfiguredMarketplaceSnapshotIssue { + marketplace_name: configured_name.clone(), + path: PathBuf::from(""), + message: "configured local marketplace source is missing or empty".to_string(), + }); continue; } let Some(root) = resolve_configured_marketplace_root( @@ -381,11 +457,16 @@ fn configured_marketplace_snapshot_issues( }; match find_marketplace_manifest_path(&root) { Some(path) => manifest_paths.push((configured_name.clone(), path)), - None => issues.push(ConfiguredMarketplaceSnapshotIssue { - marketplace_name: configured_name.clone(), - path: root, - message: "marketplace root does not contain a supported manifest".to_string(), - }), + None => { + if is_implicit_system_marketplace_root(configured_name, codex_home, &root) { + continue; + } + issues.push(ConfiguredMarketplaceSnapshotIssue { + marketplace_name: configured_name.clone(), + path: root, + message: "marketplace root does not contain a supported manifest".to_string(), + }); + } } } @@ -403,3 +484,41 @@ fn configured_marketplace_snapshot_issues( } issues } + +fn is_implicit_system_marketplace_root( + marketplace_name: &str, + _codex_home: &Path, + root: &Path, +) -> bool { + if matches!( + marketplace_name, + OPENAI_BUNDLED_MARKETPLACE_NAME | OPENAI_BUNDLED_ALPHA_MARKETPLACE_NAME + ) && path_ends_with(root, &[".tmp", "bundled-marketplaces", marketplace_name]) + { + return true; + } + + marketplace_name == OPENAI_PRIMARY_RUNTIME_MARKETPLACE_NAME + && path_ends_with( + root, + &[ + "codex-runtimes", + "codex-primary-runtime", + "plugins", + marketplace_name, + ], + ) +} + +fn path_ends_with(path: &Path, suffix: &[&str]) -> bool { + let path_components = path + .components() + .map(|component| component.as_os_str().to_string_lossy().into_owned()) + .collect::>(); + path_components.as_slice().ends_with( + &suffix + .iter() + .map(std::string::ToString::to_string) + .collect::>(), + ) +} diff --git a/codex-rs/cli/tests/plugin_cli.rs b/codex-rs/cli/tests/plugin_cli.rs index 9829e4df07..5719b8f103 100644 --- a/codex-rs/cli/tests/plugin_cli.rs +++ b/codex-rs/cli/tests/plugin_cli.rs @@ -7,9 +7,21 @@ use predicates::str::contains; use std::path::Path; use tempfile::TempDir; +const MARKETPLACE_HEADER: &str = "MARKETPLACE"; +const MARKETPLACE_LIST_HEADER: &str = "MARKETPLACE ROOT"; + +fn marketplace_list_row(marketplace_name: &str, root: &Path) -> String { + format!( + "{marketplace_name: Result { let mut cmd = assert_cmd::Command::new(codex_utils_cargo_bin::cargo_bin("codex")?); cmd.env("CODEX_HOME", codex_home); + cmd.env("HOME", codex_home); Ok(cmd) } @@ -40,11 +52,30 @@ plugins = true Ok(()) } -fn write_marketplace_source(source: &Path) -> Result<()> { - std::fs::create_dir_all(source.join(".agents/plugins"))?; - std::fs::create_dir_all(source.join("plugins/sample/.codex-plugin"))?; +fn write_marketplace_source_with_manifest(source: &Path, marketplace_manifest: &str) -> Result<()> { + std::fs::create_dir_all(source.join(".agents").join("plugins"))?; + std::fs::create_dir_all(source.join("plugins").join("sample").join(".codex-plugin"))?; std::fs::write( - source.join(".agents/plugins/marketplace.json"), + source + .join(".agents") + .join("plugins") + .join("marketplace.json"), + marketplace_manifest, + )?; + std::fs::write( + source + .join("plugins") + .join("sample") + .join(".codex-plugin") + .join("plugin.json"), + r#"{"name":"sample","version":"1.2.3","description":"Sample plugin"}"#, + )?; + Ok(()) +} + +fn write_marketplace_source(source: &Path) -> Result<()> { + write_marketplace_source_with_manifest( + source, r#"{ "name": "debug", "plugins": [ @@ -57,12 +88,28 @@ fn write_marketplace_source(source: &Path) -> Result<()> { } ] }"#, - )?; - std::fs::write( - source.join("plugins/sample/.codex-plugin/plugin.json"), - r#"{"name":"sample","description":"Sample plugin"}"#, - )?; - Ok(()) + ) +} + +fn write_marketplace_source_with_explicit_empty_products(source: &Path) -> Result<()> { + write_marketplace_source_with_manifest( + source, + r#"{ + "name": "debug", + "plugins": [ + { + "name": "sample", + "source": { + "source": "local", + "path": "./plugins/sample" + }, + "policy": { + "products": [] + } + } + ] +}"#, + ) } fn setup_local_marketplace() -> Result<(TempDir, TempDir)> { @@ -87,6 +134,20 @@ fn setup_unconfigured_local_marketplace() -> Result<(TempDir, TempDir)> { Ok((codex_home, source)) } +fn setup_local_marketplace_with_explicit_empty_products() -> Result<(TempDir, TempDir)> { + let codex_home = TempDir::new()?; + let source = TempDir::new()?; + write_plugins_enabled_config(codex_home.path())?; + write_marketplace_source_with_explicit_empty_products(source.path())?; + let source_path = source.path().to_string_lossy().into_owned(); + record_user_marketplace( + codex_home.path(), + "debug", + &configured_local_marketplace(&source_path), + )?; + Ok((codex_home, source)) +} + fn setup_configured_marketplace_without_manifest() -> Result<(TempDir, TempDir)> { let codex_home = TempDir::new()?; let source = TempDir::new()?; @@ -104,9 +165,13 @@ fn setup_configured_marketplace_with_malformed_manifest() -> Result<(TempDir, Te let codex_home = TempDir::new()?; let source = TempDir::new()?; write_plugins_enabled_config(codex_home.path())?; - std::fs::create_dir_all(source.path().join(".agents/plugins"))?; + std::fs::create_dir_all(source.path().join(".agents").join("plugins"))?; std::fs::write( - source.path().join(".agents/plugins/marketplace.json"), + source + .path() + .join(".agents") + .join("plugins") + .join("marketplace.json"), "{not valid json", )?; let source_path = source.path().to_string_lossy().into_owned(); @@ -118,30 +183,328 @@ fn setup_configured_marketplace_with_malformed_manifest() -> Result<(TempDir, Te Ok((codex_home, source)) } +fn setup_local_marketplace_with_implicit_system_roots() -> Result<(TempDir, TempDir, TempDir)> { + let (codex_home, source) = setup_local_marketplace()?; + + let bundled_root = codex_home + .path() + .join(".tmp") + .join("bundled-marketplaces") + .join("openai-bundled"); + std::fs::create_dir_all(&bundled_root)?; + let bundled_source = bundled_root.display().to_string(); + record_user_marketplace( + codex_home.path(), + "openai-bundled", + &configured_local_marketplace(&bundled_source), + )?; + + let cache_home = TempDir::new()?; + let runtime_root = cache_home + .path() + .join("codex-runtimes") + .join("codex-primary-runtime") + .join("plugins") + .join("openai-primary-runtime"); + std::fs::create_dir_all(&runtime_root)?; + let runtime_source = runtime_root.display().to_string(); + record_user_marketplace( + codex_home.path(), + "openai-primary-runtime", + &configured_local_marketplace(&runtime_source), + )?; + + Ok((codex_home, source, cache_home)) +} + +fn setup_custom_marketplace_under_implicit_system_root() -> Result<(TempDir, std::path::PathBuf)> { + let codex_home = TempDir::new()?; + write_plugins_enabled_config(codex_home.path())?; + + let custom_root = codex_home + .path() + .join(".tmp") + .join("bundled-marketplaces") + .join("custom-marketplace"); + std::fs::create_dir_all(&custom_root)?; + let custom_source = custom_root.display().to_string(); + record_user_marketplace( + codex_home.path(), + "custom-marketplace", + &configured_local_marketplace(&custom_source), + )?; + + Ok((codex_home, custom_root)) +} + +fn remove_installed_plugin_config(codex_home: &Path, plugin_key: &str) -> Result<()> { + let config_path = codex_home.join(CONFIG_TOML_FILE); + let plugin_header = format!("[plugins.\"{plugin_key}\"]"); + let config = std::fs::read_to_string(&config_path)?; + let mut rewritten = Vec::new(); + let mut skipping = false; + + for line in config.lines() { + if line == plugin_header { + skipping = true; + continue; + } + if skipping && line.starts_with('[') { + skipping = false; + } + if !skipping { + rewritten.push(line); + } + } + + std::fs::write(config_path, format!("{}\n", rewritten.join("\n")))?; + Ok(()) +} + +fn setup_configured_local_marketplace_with_missing_source() -> Result { + let codex_home = TempDir::new()?; + std::fs::write( + codex_home.path().join(CONFIG_TOML_FILE), + r#"[features] +plugins = true + +[marketplaces.debug] +source_type = "local" +"#, + )?; + Ok(codex_home) +} + +fn setup_configured_local_marketplace_with_invalid_name() -> Result { + let codex_home = TempDir::new()?; + std::fs::write( + codex_home.path().join(CONFIG_TOML_FILE), + r#"[features] +plugins = true + +[marketplaces."bad/name"] +source_type = "local" +source = "/tmp/debug" +"#, + )?; + Ok(codex_home) +} + +fn assert_configured_marketplace_snapshot_failure( + assert: assert_cmd::assert::Assert, + source: &Path, + detail: &str, +) { + assert + .failure() + .stderr(contains( + "failed to load configured marketplace snapshot(s):", + )) + .stderr(contains("`debug`")) + .stderr(contains(source.display().to_string())) + .stderr(contains(detail)); +} + +fn assert_marketplace_failure( + assert: assert_cmd::assert::Assert, + marketplace_name: &str, + source: &Path, + detail: &str, +) { + assert + .failure() + .stderr(contains("failed to load marketplace(s):")) + .stderr(contains(format!("`{marketplace_name}`"))) + .stderr(contains(source.display().to_string())) + .stderr(contains(detail)); +} + #[tokio::test] async fn marketplace_list_shows_configured_marketplace_names() -> Result<()> { let (codex_home, source) = setup_local_marketplace()?; + let expected_row = marketplace_list_row("debug", source.path()); codex_command(codex_home.path())? .args(["plugin", "marketplace", "list"]) .assert() .success() - .stdout(contains("debug")) - .stdout(contains(source.path().display().to_string())); + .stdout(contains(MARKETPLACE_LIST_HEADER)) + .stdout(contains(&expected_row)) + .stdout(contains("\t").not()); Ok(()) } #[tokio::test] -async fn plugin_list_shows_plugins_grouped_by_marketplace() -> Result<()> { - let (codex_home, _source) = setup_local_marketplace()?; +async fn marketplace_list_includes_home_marketplace_when_present() -> Result<()> { + let codex_home = TempDir::new()?; + let home = TempDir::new()?; + write_marketplace_source(home.path())?; + write_plugins_enabled_config(codex_home.path())?; + let expected_row = marketplace_list_row("debug", home.path()); + + codex_command(codex_home.path())? + .env("HOME", home.path()) + .args(["plugin", "marketplace", "list"]) + .assert() + .success() + .stdout(contains(MARKETPLACE_LIST_HEADER)) + .stdout(contains(&expected_row)) + .stdout(contains("\t").not()); + + Ok(()) +} + +#[tokio::test] +async fn marketplace_list_includes_root_when_plugins_are_filtered_out() -> Result<()> { + let (codex_home, source) = setup_local_marketplace_with_explicit_empty_products()?; + let expected_row = marketplace_list_row("debug", source.path()); + + codex_command(codex_home.path())? + .args(["plugin", "marketplace", "list"]) + .assert() + .success() + .stdout(contains(MARKETPLACE_LIST_HEADER)) + .stdout(contains(&expected_row)); + + Ok(()) +} + +#[tokio::test] +async fn marketplace_list_fails_when_configured_marketplace_snapshot_is_missing() -> Result<()> { + let (codex_home, source) = setup_configured_marketplace_without_manifest()?; + + assert_marketplace_failure( + codex_command(codex_home.path())? + .args(["plugin", "marketplace", "list"]) + .assert(), + "debug", + source.path(), + "marketplace root does not contain a supported manifest", + ); + + Ok(()) +} + +#[tokio::test] +async fn marketplace_list_fails_when_configured_marketplace_name_is_invalid() -> Result<()> { + let codex_home = setup_configured_local_marketplace_with_invalid_name()?; + + assert_marketplace_failure( + codex_command(codex_home.path())? + .args(["plugin", "marketplace", "list"]) + .assert(), + "bad/name", + Path::new(""), + "marketplace name", + ); + + Ok(()) +} + +#[tokio::test] +async fn marketplace_list_fails_when_configured_local_marketplace_source_is_missing() -> Result<()> +{ + let codex_home = setup_configured_local_marketplace_with_missing_source()?; + + codex_command(codex_home.path())? + .args(["plugin", "marketplace", "list"]) + .assert() + .failure() + .stderr(contains("failed to load marketplace(s):")) + .stderr(contains("`debug`")) + .stderr(contains("")) + .stderr(contains( + "configured local marketplace source is missing or empty", + )); + + Ok(()) +} + +#[tokio::test] +async fn marketplace_list_fails_when_home_marketplace_is_malformed() -> Result<()> { + let codex_home = TempDir::new()?; + let home = TempDir::new()?; + write_plugins_enabled_config(codex_home.path())?; + std::fs::create_dir_all(home.path().join(".agents/plugins"))?; + let home_marketplace_path = home + .path() + .join(".agents") + .join("plugins") + .join("marketplace.json"); + std::fs::write(&home_marketplace_path, "{not valid json")?; + + codex_command(codex_home.path())? + .env("HOME", home.path()) + .args(["plugin", "marketplace", "list"]) + .assert() + .failure() + .stderr(contains("failed to load marketplace(s):")) + .stderr(contains(home_marketplace_path.display().to_string())) + .stderr(contains("key must be a string")); + + Ok(()) +} + +#[tokio::test] +async fn marketplace_list_fails_when_configured_marketplace_snapshot_is_malformed() -> Result<()> { + let (codex_home, source) = setup_configured_marketplace_with_malformed_manifest()?; + + assert_marketplace_failure( + codex_command(codex_home.path())? + .args(["plugin", "marketplace", "list"]) + .assert(), + "debug", + source.path(), + "key must be a string", + ); + + Ok(()) +} + +#[tokio::test] +async fn plugin_list_prints_plugins_in_a_table() -> Result<()> { + let (codex_home, source) = setup_local_marketplace()?; + let marketplace_manifest = source + .path() + .join(".agents") + .join("plugins") + .join("marketplace.json"); + let plugin_path = source.path().join("plugins").join("sample"); codex_command(codex_home.path())? .args(["plugin", "list"]) .assert() .success() .stdout(contains("Marketplace `debug`")) - .stdout(contains("sample@debug (not installed)")); + .stdout(contains("PLUGIN")) + .stdout(contains("STATUS")) + .stdout(contains("VERSION")) + .stdout(contains("PATH")) + .stdout(contains(marketplace_manifest.display().to_string())) + .stdout(contains("sample@debug")) + .stdout(contains("not installed")) + .stdout(contains(plugin_path.display().to_string())); + + Ok(()) +} + +#[tokio::test] +async fn plugin_list_shows_installed_version_when_plugin_is_installed() -> Result<()> { + let (codex_home, _source) = setup_local_marketplace()?; + + codex_command(codex_home.path())? + .args(["plugin", "add", "sample@debug"]) + .assert() + .success(); + + codex_command(codex_home.path())? + .args(["plugin", "list"]) + .assert() + .success() + .stdout(contains("sample@debug")) + .stdout(contains("1.2.3")) + .stdout(contains("installed, enabled")); Ok(()) } @@ -151,10 +514,10 @@ async fn plugin_list_excludes_unconfigured_repo_local_marketplaces() -> Result<( let (codex_home, source) = setup_unconfigured_local_marketplace()?; codex_command_in(codex_home.path(), source.path())? - .args(["plugin", "list"]) + .args(["plugin", "list", "--marketplace", "debug"]) .assert() .success() - .stdout(contains("No marketplace plugins found.")) + .stdout(contains("No plugins found in marketplace `debug`.")) .stdout(predicates::str::is_match("sample@debug").unwrap().not()); Ok(()) @@ -164,6 +527,47 @@ async fn plugin_list_excludes_unconfigured_repo_local_marketplaces() -> Result<( async fn plugin_list_fails_when_configured_marketplace_snapshot_is_missing() -> Result<()> { let (codex_home, source) = setup_configured_marketplace_without_manifest()?; + assert_configured_marketplace_snapshot_failure( + codex_command(codex_home.path())? + .args(["plugin", "list"]) + .assert(), + source.path(), + "marketplace root does not contain a supported manifest", + ); + + Ok(()) +} + +#[tokio::test] +async fn plugin_list_ignores_implicit_system_marketplace_roots_without_manifests() -> Result<()> { + let (codex_home, source, cache_home) = setup_local_marketplace_with_implicit_system_roots()?; + + codex_command(codex_home.path())? + .env("XDG_CACHE_HOME", cache_home.path()) + .args(["plugin", "list"]) + .assert() + .success() + .stdout(contains("Marketplace `debug`")) + .stdout(contains( + source + .path() + .join(".agents") + .join("plugins") + .join("marketplace.json") + .display() + .to_string(), + )) + .stderr( + predicates::str::contains("failed to load configured marketplace snapshot(s):").not(), + ); + + Ok(()) +} + +#[tokio::test] +async fn plugin_list_fails_for_custom_marketplace_under_system_root() -> Result<()> { + let (codex_home, custom_root) = setup_custom_marketplace_under_implicit_system_root()?; + codex_command(codex_home.path())? .args(["plugin", "list"]) .assert() @@ -171,8 +575,8 @@ async fn plugin_list_fails_when_configured_marketplace_snapshot_is_missing() -> .stderr(contains( "failed to load configured marketplace snapshot(s):", )) - .stderr(contains("`debug`")) - .stderr(contains(source.path().display().to_string())) + .stderr(contains("`custom-marketplace`")) + .stderr(contains(custom_root.display().to_string())) .stderr(contains( "marketplace root does not contain a supported manifest", )); @@ -180,6 +584,28 @@ async fn plugin_list_fails_when_configured_marketplace_snapshot_is_missing() -> Ok(()) } +#[tokio::test] +async fn plugin_list_hides_version_for_cached_but_unconfigured_plugin() -> Result<()> { + let (codex_home, _source) = setup_local_marketplace()?; + + codex_command(codex_home.path())? + .args(["plugin", "add", "sample@debug"]) + .assert() + .success(); + + remove_installed_plugin_config(codex_home.path(), "sample@debug")?; + + codex_command(codex_home.path())? + .args(["plugin", "list"]) + .assert() + .success() + .stdout(contains("sample@debug")) + .stdout(contains("not installed")) + .stdout(predicates::str::contains("1.2.3").not()); + + Ok(()) +} + #[tokio::test] async fn plugin_add_and_remove_updates_installed_plugin_config() -> Result<()> { let (codex_home, _source) = setup_local_marketplace()?; @@ -224,18 +650,15 @@ async fn plugin_add_rejects_unconfigured_repo_local_marketplaces() -> Result<()> #[tokio::test] async fn plugin_add_fails_when_configured_marketplace_snapshot_is_malformed() -> Result<()> { - let (codex_home, _source) = setup_configured_marketplace_with_malformed_manifest()?; + let (codex_home, source) = setup_configured_marketplace_with_malformed_manifest()?; - codex_command(codex_home.path())? - .args(["plugin", "add", "sample@debug"]) - .assert() - .failure() - .stderr(contains( - "failed to load configured marketplace snapshot(s):", - )) - .stderr(contains("`debug`")) - .stderr(contains("invalid marketplace file")) - .stderr(contains("key must be a string")); + assert_configured_marketplace_snapshot_failure( + codex_command(codex_home.path())? + .args(["plugin", "add", "sample@debug"]) + .assert(), + source.path(), + "key must be a string", + ); Ok(()) } @@ -258,7 +681,7 @@ async fn plugin_add_reinstalls_from_configured_marketplace_snapshot() -> Result< assert!( codex_home .path() - .join("plugins/cache/debug/sample/local/.codex-plugin/plugin.json") + .join("plugins/cache/debug/sample/1.2.3/.codex-plugin/plugin.json") .is_file() ); @@ -311,7 +734,7 @@ async fn plugin_add_rejects_cached_plugins_without_authorizing_marketplace_snaps assert!( codex_home .path() - .join("plugins/cache/debug/sample/local/.codex-plugin/plugin.json") + .join("plugins/cache/debug/sample/1.2.3/.codex-plugin/plugin.json") .is_file() ); diff --git a/codex-rs/codex-api/src/endpoint/realtime_websocket/methods.rs b/codex-rs/codex-api/src/endpoint/realtime_websocket/methods.rs index 9fcca1c3e3..ad26549a26 100644 --- a/codex-rs/codex-api/src/endpoint/realtime_websocket/methods.rs +++ b/codex-rs/codex-api/src/endpoint/realtime_websocket/methods.rs @@ -993,6 +993,22 @@ mod tests { ); } + #[test] + fn parse_v1_input_transcript_turn_marked_event() { + let payload = json!({ + "type": "conversation.input_transcript.turn_marked", + "transcript": "hello realtime" + }) + .to_string(); + + assert_eq!( + parse_realtime_event(payload.as_str(), RealtimeEventParser::V1), + Some(RealtimeEvent::InputTranscriptDone(RealtimeTranscriptDone { + text: "hello realtime".to_string(), + })) + ); + } + #[test] fn parse_output_transcript_delta_event() { let payload = json!({ @@ -1581,6 +1597,10 @@ mod tests { .expect("text"); let third_json: Value = serde_json::from_str(&third).expect("json"); assert_eq!(third_json["type"], "conversation.item.create"); + assert_eq!( + third_json["item"]["content"][0]["type"], + Value::String("input_text".to_string()) + ); assert_eq!(third_json["item"]["content"][0]["text"], "hello agent"); let fourth = ws diff --git a/codex-rs/codex-api/src/endpoint/realtime_websocket/methods_v1.rs b/codex-rs/codex-api/src/endpoint/realtime_websocket/methods_v1.rs index 19e4fa203a..0f1a269082 100644 --- a/codex-rs/codex-api/src/endpoint/realtime_websocket/methods_v1.rs +++ b/codex-rs/codex-api/src/endpoint/realtime_websocket/methods_v1.rs @@ -21,7 +21,7 @@ pub(super) fn conversation_item_create_message(text: String) -> RealtimeOutbound r#type: ConversationItemType::Message, role: ConversationRole::User, content: vec![ConversationItemContent { - r#type: ConversationContentType::Text, + r#type: ConversationContentType::InputText, text, }], }), diff --git a/codex-rs/codex-api/src/endpoint/realtime_websocket/protocol.rs b/codex-rs/codex-api/src/endpoint/realtime_websocket/protocol.rs index d689f6ea96..5df4c0c503 100644 --- a/codex-rs/codex-api/src/endpoint/realtime_websocket/protocol.rs +++ b/codex-rs/codex-api/src/endpoint/realtime_websocket/protocol.rs @@ -199,7 +199,6 @@ pub(super) struct ConversationItemContent { #[derive(Debug, Clone, Copy, Serialize)] #[serde(rename_all = "snake_case")] pub(super) enum ConversationContentType { - Text, InputText, } diff --git a/codex-rs/codex-api/src/endpoint/realtime_websocket/protocol_v1.rs b/codex-rs/codex-api/src/endpoint/realtime_websocket/protocol_v1.rs index 3c1d25aed7..a464852244 100644 --- a/codex-rs/codex-api/src/endpoint/realtime_websocket/protocol_v1.rs +++ b/codex-rs/codex-api/src/endpoint/realtime_websocket/protocol_v1.rs @@ -43,7 +43,8 @@ pub(super) fn parse_realtime_event_v1(payload: &str) -> Option { | "conversation.item.input_audio_transcription.delta" => { parse_transcript_delta_event(&parsed, "delta").map(RealtimeEvent::InputTranscriptDelta) } - "conversation.item.input_audio_transcription.completed" => { + "conversation.input_transcript.turn_marked" + | "conversation.item.input_audio_transcription.completed" => { parse_transcript_done_event(&parsed, "transcript") .map(RealtimeEvent::InputTranscriptDone) } diff --git a/codex-rs/codex-api/tests/models_integration.rs b/codex-rs/codex-api/tests/models_integration.rs index d2b31180b9..b1f6f6d4bb 100644 --- a/codex-rs/codex-api/tests/models_integration.rs +++ b/codex-rs/codex-api/tests/models_integration.rs @@ -76,6 +76,7 @@ async fn models_client_hits_models_endpoint() { priority: 1, additional_speed_tiers: Vec::new(), service_tiers: Vec::new(), + default_service_tier: None, upgrade: None, base_instructions: "base instructions".to_string(), model_messages: None, diff --git a/codex-rs/config/Cargo.toml b/codex-rs/config/Cargo.toml index c345f31c6e..f77a76b764 100644 --- a/codex-rs/config/Cargo.toml +++ b/codex-rs/config/Cargo.toml @@ -28,6 +28,7 @@ codex-utils-path = { workspace = true } dunce = { workspace = true } futures = { workspace = true, features = ["alloc", "std"] } gethostname = { workspace = true } +indexmap = { workspace = true, features = ["serde"] } multimap = { workspace = true } prost = "0.14.3" schemars = { workspace = true } @@ -38,7 +39,7 @@ serde_path_to_error = { workspace = true } sha2 = { workspace = true } thiserror = { workspace = true } tokio = { workspace = true, features = ["fs"] } -toml = { workspace = true } +toml = { workspace = true, features = ["preserve_order"] } toml_edit = { workspace = true } tonic = { workspace = true } tonic-prost = { workspace = true } diff --git a/codex-rs/config/src/config_toml.rs b/codex-rs/config/src/config_toml.rs index 43f75ffc28..a4d384b5f3 100644 --- a/codex-rs/config/src/config_toml.rs +++ b/codex-rs/config/src/config_toml.rs @@ -359,7 +359,7 @@ pub struct ConfigToml { pub personality: Option, /// Optional explicit service tier request id for new turns (for example - /// `priority` or `flex`; legacy `fast` also works). + /// `default`, `priority`, or `flex`; legacy `fast` also works). pub service_tier: Option, /// Base URL for requests to ChatGPT (as opposed to the OpenAI API). diff --git a/codex-rs/config/src/hook_config.rs b/codex-rs/config/src/hook_config.rs index 4d1329229f..eee66896af 100644 --- a/codex-rs/config/src/hook_config.rs +++ b/codex-rs/config/src/hook_config.rs @@ -47,6 +47,8 @@ pub struct HookEventsToml { pub user_prompt_submit: Vec, #[serde(rename = "SubagentStart", default)] pub subagent_start: Vec, + #[serde(rename = "SubagentStop", default)] + pub subagent_stop: Vec, #[serde(rename = "Stop", default)] pub stop: Vec, } @@ -62,6 +64,7 @@ impl HookEventsToml { session_start, user_prompt_submit, subagent_start, + subagent_stop, stop, } = self; pre_tool_use.is_empty() @@ -72,6 +75,7 @@ impl HookEventsToml { && session_start.is_empty() && user_prompt_submit.is_empty() && subagent_start.is_empty() + && subagent_stop.is_empty() && stop.is_empty() } @@ -85,6 +89,7 @@ impl HookEventsToml { session_start, user_prompt_submit, subagent_start, + subagent_stop, stop, } = self; [ @@ -96,6 +101,7 @@ impl HookEventsToml { session_start, user_prompt_submit, subagent_start, + subagent_stop, stop, ] .into_iter() @@ -104,7 +110,7 @@ impl HookEventsToml { .sum() } - pub fn into_matcher_groups(self) -> [(HookEventName, Vec); 9] { + pub fn into_matcher_groups(self) -> [(HookEventName, Vec); 10] { [ (HookEventName::PreToolUse, self.pre_tool_use), (HookEventName::PermissionRequest, self.permission_request), @@ -114,6 +120,7 @@ impl HookEventsToml { (HookEventName::SessionStart, self.session_start), (HookEventName::UserPromptSubmit, self.user_prompt_submit), (HookEventName::SubagentStart, self.subagent_start), + (HookEventName::SubagentStop, self.subagent_stop), (HookEventName::Stop, self.stop), ] } diff --git a/codex-rs/config/src/permissions_toml.rs b/codex-rs/config/src/permissions_toml.rs index 60ec9e128d..a4ef5d266e 100644 --- a/codex-rs/config/src/permissions_toml.rs +++ b/codex-rs/config/src/permissions_toml.rs @@ -1,12 +1,18 @@ use std::collections::BTreeMap; use crate::merge::merge_toml_values; +use codex_network_proxy::InjectedHeaderConfig; +use codex_network_proxy::MitmHookActionsConfig; +use codex_network_proxy::MitmHookBodyConfig; +use codex_network_proxy::MitmHookConfig; +use codex_network_proxy::MitmHookMatchConfig; use codex_network_proxy::NetworkDomainPermission as ProxyNetworkDomainPermission; use codex_network_proxy::NetworkMode; use codex_network_proxy::NetworkProxyConfig; use codex_network_proxy::NetworkUnixSocketPermission as ProxyNetworkUnixSocketPermission; use codex_network_proxy::normalize_host; use codex_protocol::permissions::FileSystemAccessMode; +use indexmap::IndexMap; use schemars::JsonSchema; use serde::Deserialize; use serde::Serialize; @@ -350,6 +356,38 @@ pub struct NetworkToml { pub domains: Option, pub unix_sockets: Option, pub allow_local_binding: Option, + pub mitm: Option, +} + +#[derive(Serialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct NetworkMitmToml { + #[schemars(with = "Option>")] + pub hooks: Option>, + #[schemars(with = "Option>")] + pub actions: Option>, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct NetworkMitmTomlUnchecked { + pub hooks: Option>, + pub actions: Option>, +} + +#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)] +#[schemars(deny_unknown_fields)] +pub struct NetworkMitmHookToml { + pub host: String, + pub methods: Vec, + pub path_prefixes: Vec, + #[serde(default)] + pub query: BTreeMap>, + #[serde(default)] + pub headers: BTreeMap>, + #[schemars(with = "Option")] + pub body: Option, + pub action: Vec, } #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)] @@ -359,6 +397,114 @@ enum NetworkModeSchema { Full, } +#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)] +#[serde(default)] +pub struct NetworkMitmActionToml { + pub strip_request_headers: Vec, + pub inject_request_headers: Vec, +} + +#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)] +#[serde(default)] +pub struct NetworkMitmInjectedHeaderToml { + pub name: String, + pub secret_env_var: Option, + pub secret_file: Option, + pub prefix: Option, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema)] +#[serde(transparent)] +struct MitmHookBodyConfigSchema(pub serde_json::Value); + +impl<'de> Deserialize<'de> for NetworkMitmToml { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let unchecked = NetworkMitmTomlUnchecked::deserialize(deserializer)?; + let mitm = Self { + hooks: unchecked.hooks, + actions: unchecked.actions, + }; + mitm.validate_action_definitions() + .map_err(serde::de::Error::custom)?; + Ok(mitm) + } +} + +impl NetworkMitmToml { + pub fn validate_action_definitions(&self) -> Result<(), String> { + if let Some(actions) = self.actions.as_ref() { + for (action_name, action) in actions { + if action.is_empty() { + return Err(format!( + "network.mitm.actions.{action_name} must define at least one operation" + )); + } + } + } + + let Some(hooks) = self.hooks.as_ref() else { + return Ok(()); + }; + + for (hook_name, hook) in hooks { + if hook.action.is_empty() { + return Err(format!( + "network.mitm.hooks.{hook_name}.action must not be empty" + )); + } + } + + Ok(()) + } + + pub fn validate_action_references( + &self, + actions_by_name: &IndexMap, + ) -> Result<(), String> { + self.validate_action_definitions()?; + + let Some(hooks) = self.hooks.as_ref() else { + return Ok(()); + }; + + for (hook_name, hook) in hooks { + for action_name in &hook.action { + if !actions_by_name.contains_key(action_name) { + return Err(format!( + "network.mitm.hooks.{hook_name}.action references undefined action `{action_name}`" + )); + } + } + } + + Ok(()) + } + + pub fn to_runtime_hooks( + &self, + actions_by_name: Option<&IndexMap>, + ) -> Vec { + self.hooks + .as_ref() + .map(|hooks| { + hooks + .values() + .map(|hook| hook.to_runtime(actions_by_name)) + .collect() + }) + .unwrap_or_default() + } +} + +impl NetworkMitmActionToml { + pub fn is_empty(&self) -> bool { + self.strip_request_headers.is_empty() && self.inject_request_headers.is_empty() + } +} + impl NetworkToml { pub fn apply_to_network_proxy_config(&self, config: &mut NetworkProxyConfig) { if let Some(enabled) = self.enabled { @@ -411,6 +557,11 @@ impl NetworkToml { if let Some(allow_local_binding) = self.allow_local_binding { config.network.allow_local_binding = allow_local_binding; } + if let Some(mitm) = self.mitm.as_ref() { + config.network.mitm_hooks = mitm.to_runtime_hooks(mitm.actions.as_ref()); + } + config.network.mitm = + config.network.mode == NetworkMode::Limited || !config.network.mitm_hooks.is_empty(); } pub fn to_network_proxy_config(&self) -> NetworkProxyConfig { @@ -420,6 +571,61 @@ impl NetworkToml { } } +impl NetworkMitmHookToml { + fn to_runtime( + &self, + actions_by_name: Option<&IndexMap>, + ) -> MitmHookConfig { + MitmHookConfig { + host: self.host.clone(), + matcher: MitmHookMatchConfig { + methods: self.methods.clone(), + path_prefixes: self.path_prefixes.clone(), + query: self.query.clone(), + headers: self.headers.clone(), + body: self.body.clone(), + }, + actions: self.selected_actions(actions_by_name), + } + } + + fn selected_actions( + &self, + actions_by_name: Option<&IndexMap>, + ) -> MitmHookActionsConfig { + let Some(actions_by_name) = actions_by_name else { + return MitmHookActionsConfig::default(); + }; + + let mut selected = MitmHookActionsConfig::default(); + for action_name in &self.action { + if let Some(action) = actions_by_name.get(action_name) { + selected + .strip_request_headers + .extend(action.strip_request_headers.clone()); + selected.inject_request_headers.extend( + action + .inject_request_headers + .iter() + .map(NetworkMitmInjectedHeaderToml::to_runtime), + ); + } + } + selected + } +} + +impl NetworkMitmInjectedHeaderToml { + fn to_runtime(&self) -> InjectedHeaderConfig { + InjectedHeaderConfig { + name: self.name.clone(), + secret_env_var: self.secret_env_var.clone(), + secret_file: self.secret_file.clone(), + prefix: self.prefix.clone(), + } + } +} + pub fn overlay_network_domain_permissions( config: &mut NetworkProxyConfig, domains: &NetworkDomainPermissionsToml, diff --git a/codex-rs/config/src/profile_toml.rs b/codex-rs/config/src/profile_toml.rs index 6cf35be68e..5f4c8d62f9 100644 --- a/codex-rs/config/src/profile_toml.rs +++ b/codex-rs/config/src/profile_toml.rs @@ -24,7 +24,7 @@ use codex_protocol::protocol::AskForApproval; pub struct ConfigProfile { pub model: Option, /// Optional explicit service tier request id for new turns (for example - /// `priority` or `flex`; legacy `fast` also works). + /// `default`, `priority`, or `flex`; legacy `fast` also works). pub service_tier: Option, /// The key in the `model_providers` map identifying the /// [`ModelProviderInfo`] to use. diff --git a/codex-rs/core-plugins/src/manager.rs b/codex-rs/core-plugins/src/manager.rs index 56b8c18bda..b2495a12c1 100644 --- a/codex-rs/core-plugins/src/manager.rs +++ b/codex-rs/core-plugins/src/manager.rs @@ -22,6 +22,7 @@ use crate::manifest::load_plugin_manifest; use crate::marketplace::MarketplaceError; use crate::marketplace::MarketplaceInterface; use crate::marketplace::MarketplaceListError; +use crate::marketplace::MarketplaceListOutcome; use crate::marketplace::MarketplacePluginAuthPolicy; use crate::marketplace::MarketplacePluginPolicy; use crate::marketplace::MarketplacePluginSource; @@ -263,6 +264,7 @@ pub struct ConfiguredMarketplacePlugin { pub id: String, pub name: String, pub local_version: Option, + pub installed_version: Option, pub source: MarketplacePluginSource, pub policy: MarketplacePluginPolicy, pub interface: Option, @@ -1207,7 +1209,7 @@ impl PluginsManager { let (installed_plugins, enabled_plugins) = self.configured_plugin_states(config); let marketplace_outcome = - list_marketplaces(&self.marketplace_roots(config, additional_roots))?; + self.discover_marketplaces_for_config(config, additional_roots)?; let mut seen_plugin_keys = HashSet::new(); let marketplaces = marketplace_outcome .marketplaces @@ -1225,15 +1227,21 @@ impl PluginsManager { if !self.restriction_product_matches(plugin.policy.products.as_deref()) { return None; } + let plugin_id = + PluginId::new(plugin.name.clone(), marketplace_name.clone()).ok(); let installed = installed_plugins.contains(&plugin_key); + let installed_version = installed.then_some(()).and_then(|_| { + plugin_id + .as_ref() + .and_then(|plugin_id| self.store.active_plugin_version(plugin_id)) + }); let enabled = enabled_plugins.contains(&plugin_key); let mut interface = plugin.interface; let mut local_version = plugin.local_version; if installed && matches!(&plugin.source, MarketplacePluginSource::Git { .. }) - && let Ok(plugin_id) = - PluginId::new(plugin.name.clone(), marketplace_name.clone()) - && let Some(plugin_root) = self.store.active_plugin_root(&plugin_id) + && let Some(plugin_id) = plugin_id.as_ref() + && let Some(plugin_root) = self.store.active_plugin_root(plugin_id) && let Some(manifest) = load_plugin_manifest(plugin_root.as_path()) { local_version = manifest.version.clone(); @@ -1251,6 +1259,7 @@ impl PluginsManager { // plugin entries from duplicate marketplace files intentionally // resolve to the first discovered source. id: plugin_key, + installed_version, installed, enabled, name: plugin.name, @@ -1278,6 +1287,18 @@ impl PluginsManager { }) } + pub fn discover_marketplaces_for_config( + &self, + config: &PluginsConfigInput, + additional_roots: &[AbsolutePathBuf], + ) -> Result { + if !config.plugins_enabled { + return Ok(MarketplaceListOutcome::default()); + } + + list_marketplaces(&self.marketplace_roots(config, additional_roots)) + } + pub async fn read_plugin_for_config( &self, config: &PluginsConfigInput, @@ -1298,6 +1319,12 @@ impl PluginsManager { let marketplace_name = plugin.plugin_id.marketplace_name.clone(); let plugin_key = plugin.plugin_id.as_key(); let (installed_plugins, enabled_plugins) = self.configured_plugin_states(config); + let installed = installed_plugins.contains(&plugin_key); + let installed_version = if installed { + self.store.active_plugin_version(&plugin.plugin_id) + } else { + None + }; let plugin = self .read_plugin_detail_for_marketplace_plugin( config, @@ -1309,6 +1336,7 @@ impl PluginsManager { .manifest .as_ref() .and_then(|manifest| manifest.version.clone()), + installed_version, source: plugin.source, policy: plugin.policy, interface: plugin.interface, @@ -1317,7 +1345,7 @@ impl PluginsManager { .as_ref() .map(|manifest| manifest.keywords.clone()) .unwrap_or_default(), - installed: installed_plugins.contains(&plugin_key), + installed, enabled: enabled_plugins.contains(&plugin_key), }, ) diff --git a/codex-rs/core-plugins/src/manager_tests.rs b/codex-rs/core-plugins/src/manager_tests.rs index 53f72ed508..fa0b485fa2 100644 --- a/codex-rs/core-plugins/src/manager_tests.rs +++ b/codex-rs/core-plugins/src/manager_tests.rs @@ -1599,6 +1599,7 @@ enabled = false id: "enabled-plugin@debug".to_string(), name: "enabled-plugin".to_string(), local_version: None, + installed_version: Some("local".to_string()), source: MarketplacePluginSource::Local { path: AbsolutePathBuf::try_from(tmp.path().join("repo/enabled-plugin")) .unwrap(), @@ -1617,6 +1618,7 @@ enabled = false id: "disabled-plugin@debug".to_string(), name: "disabled-plugin".to_string(), local_version: None, + installed_version: Some("local".to_string()), source: MarketplacePluginSource::Local { path: AbsolutePathBuf::try_from(tmp.path().join("repo/disabled-plugin"),) .unwrap(), @@ -1738,6 +1740,7 @@ plugins = true id: "default-plugin@debug".to_string(), name: "default-plugin".to_string(), local_version: None, + installed_version: None, source: MarketplacePluginSource::Local { path: AbsolutePathBuf::try_from(tmp.path().join("repo/default-plugin")).unwrap(), }, @@ -2170,6 +2173,7 @@ enabled = true id: "toolkit@debug".to_string(), name: "toolkit".to_string(), local_version: None, + installed_version: Some("local".to_string()), source: MarketplacePluginSource::Git { url: missing_remote_repo_url, path: Some("plugins/toolkit".to_string()), @@ -2287,6 +2291,7 @@ plugins = true id: "linear@openai-curated".to_string(), name: "linear".to_string(), local_version: None, + installed_version: None, source: MarketplacePluginSource::Local { path: AbsolutePathBuf::try_from(curated_root.join("plugins/linear")).unwrap(), }, @@ -2582,6 +2587,7 @@ enabled = false id: "dup-plugin@debug".to_string(), name: "dup-plugin".to_string(), local_version: None, + installed_version: None, source: MarketplacePluginSource::Local { path: AbsolutePathBuf::try_from(tmp.path().join("repo-a/from-a")).unwrap(), }, @@ -2613,6 +2619,7 @@ enabled = false id: "b-only-plugin@debug".to_string(), name: "b-only-plugin".to_string(), local_version: None, + installed_version: None, source: MarketplacePluginSource::Local { path: AbsolutePathBuf::try_from(tmp.path().join("repo-b/from-b-only")).unwrap(), }, @@ -2698,6 +2705,7 @@ enabled = true id: "sample-plugin@debug".to_string(), name: "sample-plugin".to_string(), local_version: None, + installed_version: None, source: MarketplacePluginSource::Local { path: AbsolutePathBuf::try_from(tmp.path().join("repo/sample-plugin")).unwrap(), }, diff --git a/codex-rs/core-plugins/src/marketplace.rs b/codex-rs/core-plugins/src/marketplace.rs index d85cf2c16d..49925a673f 100644 --- a/codex-rs/core-plugins/src/marketplace.rs +++ b/codex-rs/core-plugins/src/marketplace.rs @@ -698,7 +698,8 @@ pub fn plugin_interface_with_marketplace_category( interface } -fn marketplace_root_dir( +#[doc(hidden)] +pub fn marketplace_root_dir( marketplace_path: &AbsolutePathBuf, ) -> Result { for relative_path in MARKETPLACE_MANIFEST_RELATIVE_PATHS { diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 636b1fcf3e..e810ce5f7c 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -686,7 +686,7 @@ "$ref": "#/definitions/SandboxMode" }, "service_tier": { - "description": "Optional explicit service tier request id for new turns (for example `priority` or `flex`; legacy `fast` also works).", + "description": "Optional explicit service tier request id for new turns (for example `default`, `priority`, or `flex`; legacy `fast` also works).", "type": "string" }, "tools": { @@ -1129,6 +1129,13 @@ }, "type": "array" }, + "SubagentStop": { + "default": [], + "items": { + "$ref": "#/definitions/MatcherGroup" + }, + "type": "array" + }, "UserPromptSubmit": { "default": [], "items": { @@ -1577,6 +1584,118 @@ "NetworkDomainPermissionsToml": { "type": "object" }, + "NetworkMitmActionToml": { + "properties": { + "inject_request_headers": { + "default": [], + "items": { + "$ref": "#/definitions/NetworkMitmInjectedHeaderToml" + }, + "type": "array" + }, + "strip_request_headers": { + "default": [], + "items": { + "type": "string" + }, + "type": "array" + } + }, + "type": "object" + }, + "NetworkMitmHookToml": { + "additionalProperties": false, + "properties": { + "action": { + "items": { + "type": "string" + }, + "type": "array" + }, + "body": true, + "headers": { + "additionalProperties": { + "items": { + "type": "string" + }, + "type": "array" + }, + "default": {}, + "type": "object" + }, + "host": { + "type": "string" + }, + "methods": { + "items": { + "type": "string" + }, + "type": "array" + }, + "path_prefixes": { + "items": { + "type": "string" + }, + "type": "array" + }, + "query": { + "additionalProperties": { + "items": { + "type": "string" + }, + "type": "array" + }, + "default": {}, + "type": "object" + } + }, + "required": [ + "action", + "host", + "methods", + "path_prefixes" + ], + "type": "object" + }, + "NetworkMitmInjectedHeaderToml": { + "properties": { + "name": { + "default": "", + "type": "string" + }, + "prefix": { + "default": null, + "type": "string" + }, + "secret_env_var": { + "default": null, + "type": "string" + }, + "secret_file": { + "default": null, + "type": "string" + } + }, + "type": "object" + }, + "NetworkMitmToml": { + "additionalProperties": false, + "properties": { + "actions": { + "additionalProperties": { + "$ref": "#/definitions/NetworkMitmActionToml" + }, + "type": "object" + }, + "hooks": { + "additionalProperties": { + "$ref": "#/definitions/NetworkMitmHookToml" + }, + "type": "object" + } + }, + "type": "object" + }, "NetworkModeSchema": { "enum": [ "limited", @@ -1680,6 +1799,9 @@ "enabled": { "type": "boolean" }, + "mitm": { + "$ref": "#/definitions/NetworkMitmToml" + }, "mode": { "$ref": "#/definitions/NetworkModeSchema" }, @@ -4776,7 +4898,7 @@ "description": "Sandbox configuration to apply if `sandbox` is `WorkspaceWrite`." }, "service_tier": { - "description": "Optional explicit service tier request id for new turns (for example `priority` or `flex`; legacy `fast` also works).", + "description": "Optional explicit service tier request id for new turns (for example `default`, `priority`, or `flex`; legacy `fast` also works).", "type": "string" }, "shell_environment_policy": { @@ -4876,4 +4998,4 @@ }, "title": "ConfigToml", "type": "object" -} +} \ No newline at end of file diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index e3569e6d18..cbffab7b33 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -748,8 +748,7 @@ impl ModelClient { prompt.output_schema_strict, ); let prompt_cache_key = Some(self.state.thread_id.to_string()); - let service_tier = - service_tier.filter(|service_tier| model_info.supports_service_tier(service_tier)); + let service_tier = model_info.service_tier_for_request(service_tier); let request = ResponsesApiRequest { model: model_info.slug.clone(), instructions: instructions.clone(), diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs index 19fd762da9..ccde74afe3 100644 --- a/codex-rs/core/src/config/config_tests.rs +++ b/codex-rs/core/src/config/config_tests.rs @@ -26,6 +26,9 @@ use codex_config::permissions_toml::FilesystemPermissionToml; use codex_config::permissions_toml::FilesystemPermissionsToml; use codex_config::permissions_toml::NetworkDomainPermissionToml; use codex_config::permissions_toml::NetworkDomainPermissionsToml; +use codex_config::permissions_toml::NetworkMitmActionToml; +use codex_config::permissions_toml::NetworkMitmHookToml; +use codex_config::permissions_toml::NetworkMitmToml; use codex_config::permissions_toml::NetworkToml; use codex_config::permissions_toml::PermissionProfileToml; use codex_config::permissions_toml::PermissionsToml; @@ -70,6 +73,7 @@ use codex_model_provider_info::OLLAMA_OSS_PROVIDER_ID; use codex_model_provider_info::WireApi; use codex_models_manager::bundled_models_response; use codex_network_proxy::NetworkMode; +use codex_protocol::config_types::SERVICE_TIER_DEFAULT_REQUEST_VALUE; use codex_protocol::config_types::ServiceTier; use codex_protocol::models::ActivePermissionProfile; use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_DANGER_FULL_ACCESS; @@ -95,6 +99,7 @@ use core_test_support::PathBufExt; use core_test_support::PathExt; use core_test_support::TempDirExt; use core_test_support::test_absolute_path; +use indexmap::IndexMap; use pretty_assertions::assert_eq; use rmcp::model::ElicitationCapability; use rmcp::model::FormElicitationCapability; @@ -759,6 +764,15 @@ mode = "full" [permissions.dev.network.domains] "openai.com" = "allow" + +[permissions.dev.network.mitm.hooks.github_write] +host = "api.github.com" +methods = ["POST", "PUT"] +path_prefixes = ["/repos/openai/"] +action = ["strip_auth"] + +[permissions.dev.network.mitm.actions.strip_auth] +strip_request_headers = ["authorization"] "#; let cfg: ConfigToml = toml::from_str(toml).expect("TOML deserialization should succeed for permissions profiles"); @@ -816,6 +830,27 @@ mode = "full" }), unix_sockets: None, allow_local_binding: None, + mitm: Some(NetworkMitmToml { + hooks: Some(IndexMap::from([( + "github_write".to_string(), + NetworkMitmHookToml { + host: "api.github.com".to_string(), + methods: vec!["POST".to_string(), "PUT".to_string()], + path_prefixes: vec!["/repos/openai/".to_string()], + query: BTreeMap::new(), + headers: BTreeMap::new(), + body: None, + action: vec!["strip_auth".to_string()], + }, + )])), + actions: Some(IndexMap::from([( + "strip_auth".to_string(), + NetworkMitmActionToml { + strip_request_headers: vec!["authorization".to_string()], + inject_request_headers: Vec::new(), + }, + )])), + }), }), }, )]), @@ -823,6 +858,140 @@ mode = "full" ); } +#[test] +fn config_toml_rejects_empty_mitm_action_reference_list() { + let toml = r#" +default_permissions = "workspace" + +[permissions.workspace.network.mitm.hooks.github_write] +host = "api.github.com" +methods = ["POST"] +path_prefixes = ["/repos/openai/"] +action = [] + +[permissions.workspace.network.mitm.actions.strip_auth] +strip_request_headers = ["authorization"] +"#; + + let err = + toml::from_str::(toml).expect_err("empty MITM action refs should fail closed"); + + assert!( + err.to_string() + .contains("network.mitm.hooks.github_write.action must not be empty"), + "{err}" + ); +} + +#[test] +fn config_toml_rejects_empty_mitm_action_definition() { + let toml = r#" +default_permissions = "workspace" + +[permissions.workspace.network.mitm.hooks.github_write] +host = "api.github.com" +methods = ["POST"] +path_prefixes = ["/repos/openai/"] +action = ["strip_auth"] + +[permissions.workspace.network.mitm.actions.strip_auth] +"#; + + let err = toml::from_str::(toml) + .expect_err("empty MITM action definitions should fail closed"); + + assert!( + err.to_string() + .contains("network.mitm.actions.strip_auth must define at least one operation"), + "{err}" + ); +} + +#[test] +fn permissions_profile_network_to_proxy_config_preserves_mitm_hooks() { + let network = NetworkToml { + mode: Some(NetworkMode::Full), + mitm: Some(NetworkMitmToml { + hooks: Some(IndexMap::from([( + "github_write".to_string(), + NetworkMitmHookToml { + host: "api.github.com".to_string(), + methods: vec!["POST".to_string()], + path_prefixes: vec!["/repos/openai/".to_string()], + action: vec!["strip_auth".to_string()], + ..NetworkMitmHookToml::default() + }, + )])), + actions: Some(IndexMap::from([( + "strip_auth".to_string(), + NetworkMitmActionToml { + strip_request_headers: vec!["authorization".to_string()], + inject_request_headers: Vec::new(), + }, + )])), + }), + ..NetworkToml::default() + }; + + let config = network.to_network_proxy_config(); + + assert_eq!(config.network.mode, NetworkMode::Full); + assert!(config.network.mitm); + assert_eq!(config.network.mitm_hooks.len(), 1); + assert_eq!(config.network.mitm_hooks[0].host, "api.github.com"); + assert_eq!( + config.network.mitm_hooks[0].matcher.methods, + vec!["POST".to_string()] + ); + assert_eq!( + config.network.mitm_hooks[0].actions.strip_request_headers, + vec!["authorization".to_string()] + ); +} + +#[test] +fn permissions_profile_network_to_proxy_config_preserves_mitm_hook_declaration_order() { + let toml = r#" +default_permissions = "workspace" + +[permissions.workspace.network.mitm.actions.noop] +strip_request_headers = ["authorization"] + +[permissions.workspace.network.mitm.hooks.z_first] +host = "api.github.com" +methods = ["POST"] +path_prefixes = ["/repos/openai/"] +action = ["noop"] + +[permissions.workspace.network.mitm.hooks.a_second] +host = "api.github.com" +methods = ["POST"] +path_prefixes = ["/repos/"] +action = ["noop"] +"#; + let cfg: ConfigToml = toml::from_str(toml).expect("permissions profile should deserialize"); + let permissions = cfg.permissions.expect("permissions should deserialize"); + let network = permissions + .entries + .get("workspace") + .expect("workspace profile should exist") + .network + .as_ref() + .expect("network profile should exist"); + + let config = network.to_network_proxy_config(); + + assert_eq!(config.network.mitm_hooks.len(), 2); + assert_eq!( + config.network.mitm_hooks[0].matcher.path_prefixes, + vec!["/repos/openai/".to_string()] + ); + assert_eq!( + config.network.mitm_hooks[1].matcher.path_prefixes, + vec!["/repos/".to_string()] + ); +} + #[tokio::test] async fn permissions_profiles_proxy_policy_does_not_start_managed_network_proxy_without_feature() -> std::io::Result<()> { @@ -8277,7 +8446,7 @@ alpha = "one\ntwo" } #[tokio::test] -async fn explicit_null_service_tier_override_sets_fast_default_opt_out() -> std::io::Result<()> { +async fn explicit_null_service_tier_override_maps_to_default_service_tier() -> std::io::Result<()> { let fixture = create_test_fixture()?; let config = Config::load_from_base_config_with_overrides( @@ -8291,8 +8460,33 @@ async fn explicit_null_service_tier_override_sets_fast_default_opt_out() -> std: ) .await?; - assert_eq!(config.service_tier, None); - assert_eq!(config.notices.fast_default_opt_out, Some(true)); + assert_eq!( + config.service_tier, + Some(SERVICE_TIER_DEFAULT_REQUEST_VALUE.to_string()) + ); + assert_eq!(config.notices.fast_default_opt_out, None); + Ok(()) +} + +#[tokio::test] +async fn default_service_tier_override_uses_default_request_value() -> std::io::Result<()> { + let fixture = create_test_fixture()?; + + let config = Config::load_from_base_config_with_overrides( + fixture.cfg.clone(), + ConfigOverrides { + cwd: Some(fixture.cwd_path()), + service_tier: Some(Some("default".to_string())), + ..Default::default() + }, + fixture.codex_home(), + ) + .await?; + + assert_eq!( + config.service_tier, + Some(SERVICE_TIER_DEFAULT_REQUEST_VALUE.to_string()) + ); Ok(()) } @@ -9712,6 +9906,73 @@ async fn explicit_sandbox_mode_falls_back_when_disallowed_by_requirements() -> s Ok(()) } +#[tokio::test] +async fn danger_full_access_with_never_is_rejected_when_requirements_force_read_only() +-> std::io::Result<()> { + let codex_home = TempDir::new()?; + std::fs::write( + codex_home.path().join(CONFIG_TOML_FILE), + r#"approval_policy = "never" +sandbox_mode = "danger-full-access" +"#, + )?; + + let err = ConfigBuilder::without_managed_config_for_tests() + .codex_home(codex_home.path().to_path_buf()) + .fallback_cwd(Some(codex_home.path().to_path_buf())) + .cloud_requirements(CloudRequirementsLoader::new(async { + Ok(Some(codex_config::ConfigRequirementsToml { + allowed_sandbox_modes: Some(vec![codex_config::SandboxModeRequirement::ReadOnly]), + ..Default::default() + })) + })) + .build() + .await + .expect_err("requirements-constrained yolo should require sandbox approval"); + + assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput); + assert_eq!( + err.to_string(), + "`approval_policy = \"never\"` cannot be used because requirements do not allow `sandbox_mode = \"danger-full-access\"`; Codex would fall back to read-only permissions with approvals disabled. Choose an `approval_policy` based on what you need, such as `on-request`, or choose an allowed sandbox mode." + ); + Ok(()) +} + +#[tokio::test] +async fn named_full_access_profile_with_never_is_rejected_when_requirements_force_read_only() +-> std::io::Result<()> { + let codex_home = TempDir::new()?; + std::fs::write( + codex_home.path().join(CONFIG_TOML_FILE), + r#"approval_policy = "never" +default_permissions = "dev" + +[permissions.dev.filesystem] +":root" = "write" +"#, + )?; + + let err = ConfigBuilder::without_managed_config_for_tests() + .codex_home(codex_home.path().to_path_buf()) + .fallback_cwd(Some(codex_home.path().to_path_buf())) + .cloud_requirements(CloudRequirementsLoader::new(async { + Ok(Some(codex_config::ConfigRequirementsToml { + allowed_sandbox_modes: Some(vec![codex_config::SandboxModeRequirement::ReadOnly]), + ..Default::default() + })) + })) + .build() + .await + .expect_err("requirements-constrained full-access profile should require sandbox approval"); + + assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput); + assert_eq!( + err.to_string(), + "`approval_policy = \"never\"` cannot be used because requirements do not allow `sandbox_mode = \"danger-full-access\"`; Codex would fall back to read-only permissions with approvals disabled. Choose an `approval_policy` based on what you need, such as `on-request`, or choose an allowed sandbox mode." + ); + Ok(()) +} + #[tokio::test] async fn permission_profile_override_falls_back_when_disallowed_by_requirements() -> std::io::Result<()> { diff --git a/codex-rs/core/src/config/edit.rs b/codex-rs/core/src/config/edit.rs index 5418d3b268..f467c76cf9 100644 --- a/codex-rs/core/src/config/edit.rs +++ b/codex-rs/core/src/config/edit.rs @@ -40,8 +40,6 @@ pub enum ConfigEdit { SetNoticeHideFullAccessWarning(bool), /// Toggle the Windows world-writable directories warning acknowledgement flag. SetNoticeHideWorldWritableWarning(bool), - /// Toggle the opt-out marker for Codex-managed fast defaults. - SetNoticeFastDefaultOptOut(bool), /// Toggle the rate limit model nudge acknowledgement flag. SetNoticeHideRateLimitModelNudge(bool), /// Toggle the model migration prompt acknowledgement flag. @@ -552,6 +550,8 @@ impl ConfigDocument { ConfigEdit::SetServiceTier { service_tier } => Ok(self.write_profile_value( &["service_tier"], service_tier.as_ref().map(|service_tier| { + // Keep the legacy config spelling stable. Runtime values use + // `priority`, but config.toml continues to store it as `fast`. let config_value = match ServiceTier::from_request_value(service_tier) { Some(ServiceTier::Fast) => "fast", Some(ServiceTier::Flex) => "flex", @@ -574,11 +574,6 @@ impl ConfigDocument { &[NOTICE_TABLE_KEY, "hide_world_writable_warning"], value(*acknowledged), )), - ConfigEdit::SetNoticeFastDefaultOptOut(opted_out) => Ok(self.write_value( - Scope::Global, - &[NOTICE_TABLE_KEY, "fast_default_opt_out"], - value(*opted_out), - )), ConfigEdit::SetNoticeHideRateLimitModelNudge(acknowledged) => Ok(self.write_value( Scope::Global, &[NOTICE_TABLE_KEY, "hide_rate_limit_model_nudge"], @@ -1182,12 +1177,6 @@ impl ConfigEditsBuilder { self } - pub fn set_fast_default_opt_out(mut self, opted_out: bool) -> Self { - self.edits - .push(ConfigEdit::SetNoticeFastDefaultOptOut(opted_out)); - self - } - pub fn set_hide_rate_limit_model_nudge(mut self, acknowledged: bool) -> Self { self.edits .push(ConfigEdit::SetNoticeHideRateLimitModelNudge(acknowledged)); diff --git a/codex-rs/core/src/config/edit_tests.rs b/codex-rs/core/src/config/edit_tests.rs index 751411afdf..30f82db29b 100644 --- a/codex-rs/core/src/config/edit_tests.rs +++ b/codex-rs/core/src/config/edit_tests.rs @@ -4,6 +4,7 @@ use codex_config::types::McpServerOAuthConfig; use codex_config::types::McpServerToolConfig; use codex_config::types::McpServerTransportConfig; use codex_config::types::SessionPickerViewMode; +use codex_protocol::config_types::SERVICE_TIER_DEFAULT_REQUEST_VALUE; use codex_protocol::config_types::ServiceTier; use codex_protocol::openai_models::ReasoningEffort; use pretty_assertions::assert_eq; @@ -34,6 +35,20 @@ model_reasoning_effort = "high" assert_eq!(contents, expected); } +#[test] +fn set_service_tier_saves_default_as_default() { + let tmp = tempdir().expect("tmpdir"); + let codex_home = tmp.path(); + + ConfigEditsBuilder::new(codex_home) + .set_service_tier(Some(SERVICE_TIER_DEFAULT_REQUEST_VALUE.to_string())) + .apply_blocking() + .expect("persist"); + + let contents = std::fs::read_to_string(codex_home.join(CONFIG_TOML_FILE)).expect("read config"); + assert_eq!(contents, "service_tier = \"default\"\n"); +} + #[test] fn set_service_tier_saves_priority_as_fast() { let tmp = tempdir().expect("tmpdir"); diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 434969e2c5..23cf7aca67 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -81,6 +81,7 @@ use codex_protocol::config_types::AutoCompactTokenLimitScope; use codex_protocol::config_types::ForcedLoginMethod; use codex_protocol::config_types::Personality; use codex_protocol::config_types::ReasoningSummary; +use codex_protocol::config_types::SERVICE_TIER_DEFAULT_REQUEST_VALUE; use codex_protocol::config_types::SandboxMode; use codex_protocol::config_types::ServiceTier; use codex_protocol::config_types::ShellEnvironmentPolicy; @@ -519,6 +520,7 @@ pub struct Config { pub model: Option, /// Effective service tier request id preference for new turns. + /// `default` means the user explicitly selected standard routing. pub service_tier: Option, /// Model used specifically for review sessions. @@ -3136,15 +3138,10 @@ impl Config { let forced_login_method = cfg.forced_login_method; let model = model.or(config_profile.model).or(cfg.model); - let mut notices = cfg.notice.unwrap_or_default(); + let notices = cfg.notice.unwrap_or_default(); let service_tier = match service_tier_override { Some(Some(service_tier)) => Some(service_tier), - Some(None) => { - // Preserve explicit standard/clear intent after the nested override - // collapses into `Config.service_tier = None`. - notices.fast_default_opt_out = Some(true); - None - } + Some(None) => Some(SERVICE_TIER_DEFAULT_REQUEST_VALUE.to_string()), None => config_profile.service_tier.or(cfg.service_tier), }; let service_tier = service_tier.and_then(|service_tier| { @@ -3304,6 +3301,17 @@ impl Config { &mut constrained_permission_profile, &mut startup_warnings, )?; + if permission_profile_was_constrained + && sandbox_mode_requirement_for_permission_profile(&original_permission_profile) + == SandboxModeRequirement::DangerFullAccess + && constrained_permission_profile.get() == &PermissionProfile::read_only() + && constrained_approval_policy.value() == AskForApproval::Never + { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "`approval_policy = \"never\"` cannot be used because requirements do not allow `sandbox_mode = \"danger-full-access\"`; Codex would fall back to read-only permissions with approvals disabled. Choose an `approval_policy` based on what you need, such as `on-request`, or choose an allowed sandbox mode.", + )); + } if permission_profile_was_constrained { // The selected profile no longer describes the effective // permissions after requirements forced a fallback. diff --git a/codex-rs/core/src/config/permissions.rs b/codex-rs/core/src/config/permissions.rs index 7c757d386a..3aaa7d66f8 100644 --- a/codex-rs/core/src/config/permissions.rs +++ b/codex-rs/core/src/config/permissions.rs @@ -186,6 +186,7 @@ pub(crate) fn apply_network_proxy_feature_config( } }), allow_local_binding: feature_config.allow_local_binding, + mitm: None, } .apply_to_network_proxy_config(config); } diff --git a/codex-rs/core/src/exec.rs b/codex-rs/core/src/exec.rs index a6d958b107..84ebe337c6 100644 --- a/codex-rs/core/src/exec.rs +++ b/codex-rs/core/src/exec.rs @@ -433,10 +433,10 @@ pub(crate) async fn execute_exec_request( expiration, capture_policy, sandbox, - windows_sandbox_policy_cwd: _, + windows_sandbox_policy_cwd, windows_sandbox_level, windows_sandbox_private_desktop, - permission_profile: _, + permission_profile, file_system_sandbox_policy: _, network_sandbox_policy, windows_sandbox_filesystem_overrides, @@ -465,6 +465,8 @@ pub(crate) async fn execute_exec_request( after_spawn, sandbox, &sandbox_policy, + &permission_profile, + &windows_sandbox_policy_cwd, windows_sandbox_filesystem_overrides.as_ref(), ) .await; @@ -472,6 +474,7 @@ pub(crate) async fn execute_exec_request( finalize_exec_result(raw_output_result, sandbox, duration) } +#[allow(clippy::too_many_arguments)] async fn get_raw_output_result( params: ExecParams, network_sandbox_policy: NetworkSandboxPolicy, @@ -479,14 +482,22 @@ async fn get_raw_output_result( after_spawn: Option>, #[cfg_attr(not(windows), allow(unused_variables))] sandbox: SandboxType, #[cfg_attr(not(windows), allow(unused_variables))] sandbox_policy: &SandboxPolicy, + #[cfg_attr(not(windows), allow(unused_variables))] permission_profile: &PermissionProfile, + #[cfg_attr(not(windows), allow(unused_variables))] windows_sandbox_policy_cwd: &AbsolutePathBuf, #[cfg_attr(not(windows), allow(unused_variables))] windows_sandbox_filesystem_overrides: Option< &WindowsSandboxFilesystemOverrides, >, ) -> Result { #[cfg(target_os = "windows")] if sandbox == SandboxType::WindowsRestrictedToken { - return exec_windows_sandbox(params, sandbox_policy, windows_sandbox_filesystem_overrides) - .await; + return exec_windows_sandbox( + params, + sandbox_policy, + permission_profile, + windows_sandbox_policy_cwd, + windows_sandbox_filesystem_overrides, + ) + .await; } exec(params, network_sandbox_policy, stdout_stream, after_spawn).await @@ -562,10 +573,12 @@ fn record_windows_sandbox_spawn_failure( async fn exec_windows_sandbox( params: ExecParams, sandbox_policy: &SandboxPolicy, + permission_profile: &PermissionProfile, + windows_sandbox_policy_cwd: &AbsolutePathBuf, windows_sandbox_filesystem_overrides: Option<&WindowsSandboxFilesystemOverrides>, ) -> Result { use crate::config::find_codex_home; - use codex_windows_sandbox::run_windows_sandbox_capture_elevated; + use codex_windows_sandbox::run_windows_sandbox_capture_for_permission_profile_elevated; use codex_windows_sandbox::run_windows_sandbox_capture_with_filesystem_overrides; let ExecParams { @@ -596,7 +609,8 @@ async fn exec_windows_sandbox( "failed to serialize Windows sandbox policy: {err}" ))) })?; - let sandbox_cwd = cwd.clone(); + let sandbox_cwd = windows_sandbox_policy_cwd.clone(); + let permission_profile = permission_profile.clone(); let codex_home = find_codex_home().map_err(|err| { CodexErr::Io(io::Error::other(format!( "windows sandbox: failed to resolve codex_home: {err}" @@ -620,10 +634,10 @@ async fn exec_windows_sandbox( .and_then(|overrides| overrides.write_roots_override.clone()); let spawn_res = tokio::task::spawn_blocking(move || { if use_elevated { - run_windows_sandbox_capture_elevated( - codex_windows_sandbox::ElevatedSandboxCaptureRequest { - policy_json_or_preset: policy_str.as_str(), - sandbox_policy_cwd: &sandbox_cwd, + run_windows_sandbox_capture_for_permission_profile_elevated( + codex_windows_sandbox::ElevatedSandboxProfileCaptureRequest { + permission_profile: &permission_profile, + permission_profile_cwd: &sandbox_cwd, codex_home: codex_home.as_ref(), command, cwd: &cwd, diff --git a/codex-rs/core/src/hook_runtime.rs b/codex-rs/core/src/hook_runtime.rs index 3708ea6089..047299f48e 100644 --- a/codex-rs/core/src/hook_runtime.rs +++ b/codex-rs/core/src/hook_runtime.rs @@ -14,8 +14,8 @@ use codex_hooks::PreToolUseOutcome; use codex_hooks::PreToolUseRequest; use codex_hooks::SessionStartOutcome; use codex_hooks::StartHookTarget; +use codex_hooks::StopHookTarget; use codex_hooks::StopOutcome; -use codex_hooks::StopRequest; use codex_hooks::UserPromptSubmitOutcome; use codex_hooks::UserPromptSubmitRequest; use codex_otel::HOOK_RUN_DURATION_METRIC; @@ -33,6 +33,7 @@ use codex_protocol::protocol::HookSource; use codex_protocol::protocol::HookStartedEvent; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SubAgentSource; +use codex_thread_store::ReadThreadParams; use serde_json::Value; use crate::context::ContextualUserFragment; @@ -288,6 +289,78 @@ pub(crate) async fn run_post_tool_use_hooks( outcome } +pub(crate) async fn run_turn_stop_hooks( + sess: &Arc, + turn_context: &Arc, + stop_hook_active: bool, + last_assistant_message: Option, +) -> StopOutcome { + // Resolve the stop hook kind from the session source before building the + // request. Root turns run Stop; thread-spawned child turns run SubagentStop. + let (target, transcript_path) = match &turn_context.session_source { + SessionSource::SubAgent(SubAgentSource::ThreadSpawn { + agent_role, + parent_thread_id, + .. + }) => { + let agent_type = agent_role + .clone() + .unwrap_or_else(|| crate::agent::role::DEFAULT_ROLE_NAME.to_string()); + let agent_transcript_path = sess.hook_transcript_path().await; + let parent_transcript_path = match sess + .services + .thread_store + .read_thread(ReadThreadParams { + thread_id: *parent_thread_id, + include_archived: true, + include_history: false, + }) + .await + { + Ok(thread) => thread.rollout_path, + Err(error) => { + tracing::warn!( + parent_thread_id = %parent_thread_id, + error = %error, + "failed to resolve parent transcript path for subagent hook" + ); + None + } + }; + ( + StopHookTarget::SubagentStop { + agent_id: sess.thread_id().to_string(), + agent_type, + agent_transcript_path, + }, + parent_transcript_path, + ) + } + // Internal/synthetic subagents do not expose user-configured lifecycle + // hooks, so there is no Stop or SubagentStop request to dispatch. + SessionSource::SubAgent(_) => return StopOutcome::default(), + _ => (StopHookTarget::Stop, sess.hook_transcript_path().await), + }; + let request = codex_hooks::StopRequest { + session_id: sess.session_id().into(), + turn_id: turn_context.sub_id.clone(), + #[allow(deprecated)] + cwd: turn_context.cwd.clone(), + transcript_path, + model: turn_context.model_info.slug.clone(), + permission_mode: hook_permission_mode(turn_context), + stop_hook_active, + last_assistant_message, + target, + }; + let hooks = sess.hooks(); + emit_hook_started_events(sess, turn_context, hooks.preview_stop(&request)).await; + + let mut outcome = hooks.run_stop(request).await; + emit_hook_completed_events(sess, turn_context, std::mem::take(&mut outcome.hook_events)).await; + outcome +} + pub(crate) async fn run_pre_compact_hooks( sess: &Arc, turn_context: &Arc, @@ -352,30 +425,6 @@ pub(crate) async fn run_post_compact_hooks( } } -pub(crate) async fn run_stop_hooks( - sess: &Arc, - turn_context: &Arc, - stop_hook_active: bool, - last_assistant_message: Option, -) -> StopOutcome { - let request = StopRequest { - session_id: sess.session_id().into(), - turn_id: turn_context.sub_id.clone(), - #[allow(deprecated)] - cwd: turn_context.cwd.clone(), - transcript_path: sess.hook_transcript_path().await, - model: turn_context.model_info.slug.clone(), - permission_mode: hook_permission_mode(turn_context), - stop_hook_active, - last_assistant_message, - }; - let hooks = sess.hooks(); - emit_hook_started_events(sess, turn_context, hooks.preview_stop(&request)).await; - let mut outcome = hooks.run_stop(request).await; - emit_hook_completed_events(sess, turn_context, std::mem::take(&mut outcome.hook_events)).await; - outcome -} - pub(crate) async fn run_legacy_after_agent_hook( sess: &Arc, turn_context: &Arc, @@ -638,6 +687,7 @@ fn hook_run_metric_tags(run: &HookRunSummary) -> [(&'static str, &'static str); HookEventName::SessionStart => "SessionStart", HookEventName::UserPromptSubmit => "UserPromptSubmit", HookEventName::SubagentStart => "SubagentStart", + HookEventName::SubagentStop => "SubagentStop", HookEventName::Stop => "Stop", }; let hook_source = match run.source { diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index 7b62b10b6f..5888acad31 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -138,9 +138,14 @@ pub(crate) async fn handle_mcp_tool_call( let metadata = lookup_mcp_tool_metadata(sess.as_ref(), turn_context.as_ref(), &server, &tool_name).await; - let mcp_app_resource_uri = metadata - .as_ref() - .and_then(|metadata| metadata.mcp_app_resource_uri.clone()); + let item_metadata = McpToolCallItemMetadata { + mcp_app_resource_uri: metadata + .as_ref() + .and_then(|metadata| metadata.mcp_app_resource_uri.clone()), + plugin_id: metadata + .as_ref() + .and_then(|metadata| metadata.plugin_id.clone()), + }; let app_tool_policy = if server == CODEX_APPS_MCP_SERVER_NAME { connectors::app_tool_policy( &turn_context.config, @@ -171,7 +176,7 @@ pub(crate) async fn handle_mcp_tool_call( turn_context.as_ref(), &call_id, invocation, - mcp_app_resource_uri.clone(), + item_metadata.clone(), "MCP tool call blocked by app configuration".to_string(), /*already_started*/ false, ) @@ -200,7 +205,7 @@ pub(crate) async fn handle_mcp_tool_call( turn_context.as_ref(), &call_id, invocation.clone(), - mcp_app_resource_uri.clone(), + item_metadata.clone(), ) .await; @@ -225,7 +230,7 @@ pub(crate) async fn handle_mcp_tool_call( &call_id, invocation, metadata.as_ref(), - mcp_app_resource_uri, + item_metadata, ) .await; } @@ -236,7 +241,7 @@ pub(crate) async fn handle_mcp_tool_call( turn_context.as_ref(), &call_id, invocation, - mcp_app_resource_uri.clone(), + item_metadata.clone(), message, /*already_started*/ true, ) @@ -249,7 +254,7 @@ pub(crate) async fn handle_mcp_tool_call( turn_context.as_ref(), &call_id, invocation, - mcp_app_resource_uri.clone(), + item_metadata.clone(), message, /*already_started*/ true, ) @@ -280,7 +285,7 @@ pub(crate) async fn handle_mcp_tool_call( &call_id, invocation, metadata.as_ref(), - mcp_app_resource_uri, + item_metadata, ) .await } @@ -290,13 +295,19 @@ pub(crate) struct HandledMcpToolCall { pub(crate) tool_input: JsonValue, } +#[derive(Clone)] +struct McpToolCallItemMetadata { + mcp_app_resource_uri: Option, + plugin_id: Option, +} + async fn handle_approved_mcp_tool_call( sess: &Session, turn_context: &TurnContext, call_id: &str, invocation: McpInvocation, metadata: Option<&McpToolApprovalMetadata>, - mcp_app_resource_uri: Option, + item_metadata: McpToolCallItemMetadata, ) -> HandledMcpToolCall { let server = invocation.server.clone(); maybe_mark_thread_memory_mode_polluted(sess, turn_context, &server).await; @@ -365,7 +376,7 @@ async fn handle_approved_mcp_tool_call( turn_context, call_id, invocation, - mcp_app_resource_uri, + item_metadata, duration, truncate_mcp_tool_result_for_event(&result), ) @@ -840,7 +851,7 @@ async fn notify_mcp_tool_call_started( turn_context: &TurnContext, call_id: &str, invocation: McpInvocation, - mcp_app_resource_uri: Option, + item_metadata: McpToolCallItemMetadata, ) { let McpInvocation { server, @@ -852,7 +863,8 @@ async fn notify_mcp_tool_call_started( server, tool, arguments: arguments.unwrap_or(JsonValue::Null), - mcp_app_resource_uri, + mcp_app_resource_uri: item_metadata.mcp_app_resource_uri, + plugin_id: item_metadata.plugin_id, status: McpToolCallStatus::InProgress, result: None, error: None, @@ -866,7 +878,7 @@ async fn notify_mcp_tool_call_completed( turn_context: &TurnContext, call_id: &str, invocation: McpInvocation, - mcp_app_resource_uri: Option, + item_metadata: McpToolCallItemMetadata, duration: Duration, result: Result, ) { @@ -891,7 +903,8 @@ async fn notify_mcp_tool_call_completed( server, tool, arguments: arguments.unwrap_or(JsonValue::Null), - mcp_app_resource_uri, + mcp_app_resource_uri: item_metadata.mcp_app_resource_uri, + plugin_id: item_metadata.plugin_id, status, result, error, @@ -2092,7 +2105,7 @@ async fn notify_mcp_tool_call_skip( turn_context: &TurnContext, call_id: &str, invocation: McpInvocation, - mcp_app_resource_uri: Option, + item_metadata: McpToolCallItemMetadata, message: String, already_started: bool, ) -> Result { @@ -2102,7 +2115,7 @@ async fn notify_mcp_tool_call_skip( turn_context, call_id, invocation.clone(), - mcp_app_resource_uri.clone(), + item_metadata.clone(), ) .await; } @@ -2112,7 +2125,7 @@ async fn notify_mcp_tool_call_skip( turn_context, call_id, invocation, - mcp_app_resource_uri, + item_metadata, Duration::ZERO, truncate_mcp_tool_result_for_event(&Err(message.clone())), ) diff --git a/codex-rs/core/src/mcp_tool_call_tests.rs b/codex-rs/core/src/mcp_tool_call_tests.rs index cb83600350..f9984c7f2d 100644 --- a/codex-rs/core/src/mcp_tool_call_tests.rs +++ b/codex-rs/core/src/mcp_tool_call_tests.rs @@ -1112,6 +1112,40 @@ async fn plugin_mcp_tool_call_request_meta_includes_plugin_id() { ); } +#[tokio::test] +async fn mcp_tool_call_item_includes_plugin_id() { + let (session, turn_context, rx_event) = make_session_and_context_with_rx().await; + + notify_mcp_tool_call_started( + &session, + &turn_context, + "call-plugin", + McpInvocation { + server: "sample".to_string(), + tool: "echo".to_string(), + arguments: None, + }, + McpToolCallItemMetadata { + mcp_app_resource_uri: None, + plugin_id: Some("sample@test".to_string()), + }, + ) + .await; + + let event = tokio::time::timeout(std::time::Duration::from_secs(1), rx_event.recv()) + .await + .expect("tool call item timed out") + .expect("tool call item event"); + let EventMsg::ItemStarted(item_started) = event.msg else { + panic!("expected ItemStarted event"); + }; + let TurnItem::McpToolCall(item) = item_started.item else { + panic!("expected MCP tool call item"); + }; + + assert_eq!(item.plugin_id.as_deref(), Some("sample@test")); +} + #[tokio::test] async fn codex_apps_tool_call_request_meta_includes_turn_metadata_and_codex_apps_meta() { let (_, turn_context) = make_session_and_context().await; diff --git a/codex-rs/core/src/network_proxy_loader.rs b/codex-rs/core/src/network_proxy_loader.rs index dc4b5b6b16..7d67ad7859 100644 --- a/codex-rs/core/src/network_proxy_loader.rs +++ b/codex-rs/core/src/network_proxy_loader.rs @@ -16,12 +16,16 @@ use codex_config::ConfigLayerStackOrdering; use codex_config::LoaderOverrides; use codex_config::loader::load_config_layers_state; use codex_config::merge_toml_values; +use codex_config::permissions_toml::NetworkMitmActionToml; +use codex_config::permissions_toml::NetworkMitmHookToml; +use codex_config::permissions_toml::NetworkMitmToml; use codex_config::permissions_toml::NetworkToml; use codex_config::permissions_toml::PermissionsToml; use codex_config::permissions_toml::overlay_network_domain_permissions; use codex_exec_server::LOCAL_FS; use codex_network_proxy::ConfigReloader; use codex_network_proxy::ConfigState; +use codex_network_proxy::NetworkMode; use codex_network_proxy::NetworkProxyConfig; use codex_network_proxy::NetworkProxyConstraintError; use codex_network_proxy::NetworkProxyConstraints; @@ -30,6 +34,7 @@ use codex_network_proxy::build_config_state; use codex_network_proxy::normalize_host; use codex_network_proxy::validate_policy_against_constraints; use codex_utils_absolute_path::AbsolutePathBuf; +use indexmap::IndexMap; use serde::Deserialize; use std::sync::Arc; use tokio::sync::RwLock; @@ -208,6 +213,7 @@ fn selected_network_from_tables(parsed: NetworkTablesToml) -> Result Result<()> { if let Some(network) = selected_network_from_tables(parsed)? { network.apply_to_network_proxy_config(config); @@ -215,11 +221,57 @@ fn apply_network_tables(config: &mut NetworkProxyConfig, parsed: NetworkTablesTo Ok(()) } +#[derive(Default)] +struct NetworkConfigAccumulator { + config: NetworkProxyConfig, + mitm_hooks: IndexMap, + mitm_actions: IndexMap, +} + +impl NetworkConfigAccumulator { + fn apply_network_tables(&mut self, parsed: NetworkTablesToml) -> Result<()> { + if let Some(network) = selected_network_from_tables(parsed)? { + self.apply_network(network); + } + Ok(()) + } + + fn apply_network(&mut self, mut network: NetworkToml) { + let mitm = network.mitm.take(); + network.apply_to_network_proxy_config(&mut self.config); + + if let Some(mitm) = mitm { + if let Some(actions) = mitm.actions { + self.mitm_actions.extend(actions); + } + if let Some(hooks) = mitm.hooks { + self.mitm_hooks.extend(hooks); + } + } + } + + fn finish(mut self) -> Result { + if !self.mitm_hooks.is_empty() { + let actions = self.mitm_actions; + let mitm = NetworkMitmToml { + hooks: Some(self.mitm_hooks), + actions: Some(actions.clone()), + }; + mitm.validate_action_references(&actions) + .map_err(anyhow::Error::msg)?; + self.config.network.mitm_hooks = mitm.to_runtime_hooks(Some(&actions)); + } + + self.config.network.mitm = self.config.network.mode == NetworkMode::Limited + || !self.config.network.mitm_hooks.is_empty(); + Ok(self.config) + } +} + fn config_from_layers( layers: &ConfigLayerStack, exec_policy: &codex_execpolicy::Policy, ) -> Result { - let mut config = NetworkProxyConfig::default(); let mut merged = toml::Value::Table(toml::map::Map::new()); for layer in layers.get_layers( ConfigLayerStackOrdering::LowestPrecedenceFirst, @@ -228,7 +280,9 @@ fn config_from_layers( merge_toml_values(&mut merged, &layer.config); } let parsed = network_tables_from_toml(&merged)?; - apply_network_tables(&mut config, parsed)?; + let mut accumulator = NetworkConfigAccumulator::default(); + accumulator.apply_network_tables(parsed)?; + let mut config = accumulator.finish()?; apply_exec_policy_network_rules(&mut config, exec_policy); Ok(config) } diff --git a/codex-rs/core/src/network_proxy_loader_tests.rs b/codex-rs/core/src/network_proxy_loader_tests.rs index e2f3e7b98b..33ca54019e 100644 --- a/codex-rs/core/src/network_proxy_loader_tests.rs +++ b/codex-rs/core/src/network_proxy_loader_tests.rs @@ -112,6 +112,76 @@ default_permissions = "dev" assert_eq!(config.network.denied_domains(), None); } +#[test] +fn higher_precedence_profile_network_overrides_named_mitm_actions() { + let lower_network: toml::Value = toml::from_str( + r#" +default_permissions = "workspace" + +[permissions.workspace.network] +mode = "full" + +[permissions.workspace.network.domains] +"lower.example.com" = "allow" + +[permissions.workspace.network.mitm.hooks.github_write] +host = "api.github.com" +methods = ["POST"] +path_prefixes = ["/repos/openai/"] +action = ["strip_auth"] + +[permissions.workspace.network.mitm.actions.strip_auth] +strip_request_headers = ["authorization"] +"#, + ) + .expect("lower layer should parse"); + let higher_network: toml::Value = toml::from_str( + r#" +default_permissions = "workspace" + +[permissions.workspace.network] +mode = "full" + +[permissions.workspace.network.domains] +"higher.example.com" = "allow" + +[permissions.workspace.network.mitm.actions.strip_auth] +strip_request_headers = ["x-api-key"] +"#, + ) + .expect("higher layer should parse"); + + let mut accumulator = NetworkConfigAccumulator::default(); + accumulator + .apply_network_tables( + network_tables_from_toml(&lower_network).expect("lower layer should deserialize"), + ) + .expect("lower layer should apply"); + accumulator + .apply_network_tables( + network_tables_from_toml(&higher_network).expect("higher layer should deserialize"), + ) + .expect("higher layer should apply"); + let config = accumulator.finish().expect("merged config should build"); + + assert_eq!(config.network.mode, codex_network_proxy::NetworkMode::Full); + assert!(config.network.mitm); + assert_eq!( + config.network.allowed_domains(), + Some(vec![ + "lower.example.com".to_string(), + "higher.example.com".to_string() + ]) + ); + assert_eq!(config.network.mitm_hooks.len(), 1); + assert_eq!(config.network.mitm_hooks[0].host, "api.github.com"); + assert_eq!(config.network.mitm_hooks[0].matcher.methods, vec!["POST"]); + assert_eq!( + config.network.mitm_hooks[0].actions.strip_request_headers, + vec!["x-api-key"] + ); +} + #[test] fn execpolicy_network_rules_overlay_network_lists() { let mut config = NetworkProxyConfig::default(); diff --git a/codex-rs/core/src/realtime_conversation.rs b/codex-rs/core/src/realtime_conversation.rs index 249b3ae15f..7f71142e19 100644 --- a/codex-rs/core/src/realtime_conversation.rs +++ b/codex-rs/core/src/realtime_conversation.rs @@ -641,12 +641,14 @@ async fn prepare_realtime_start( realtime_request_headers( requested_realtime_session_id.as_deref(), Some(realtime_api_key.as_str()), + version, )? } ConversationStartTransport::Webrtc { .. } => { realtime_request_headers( requested_realtime_session_id.as_deref(), /*api_key*/ None, + version, )? } }; @@ -973,9 +975,14 @@ fn realtime_api_key(auth: Option<&CodexAuth>, provider: &ModelProviderInfo) -> C fn realtime_request_headers( realtime_session_id: Option<&str>, api_key: Option<&str>, + version: RealtimeWsVersion, ) -> CodexResult> { let mut headers = HeaderMap::new(); + if version == RealtimeWsVersion::V1 { + headers.insert("openai-alpha", HeaderValue::from_static("quicksilver=v1")); + } + if let Some(realtime_session_id) = realtime_session_id && let Ok(realtime_session_id) = HeaderValue::from_str(realtime_session_id) { diff --git a/codex-rs/core/src/realtime_conversation_tests.rs b/codex-rs/core/src/realtime_conversation_tests.rs index a146c43869..b67205ef8f 100644 --- a/codex-rs/core/src/realtime_conversation_tests.rs +++ b/codex-rs/core/src/realtime_conversation_tests.rs @@ -1,9 +1,11 @@ use super::RealtimeHandoffState; use super::RealtimeSessionKind; use super::realtime_delegation_from_handoff; +use super::realtime_request_headers; use super::realtime_text_from_handoff_request; use super::wrap_realtime_delegation_input; use async_channel::bounded; +use codex_config::config_toml::RealtimeWsVersion; use codex_protocol::protocol::RealtimeHandoffRequested; use codex_protocol::protocol::RealtimeTranscriptEntry; use pretty_assertions::assert_eq; @@ -137,3 +139,28 @@ async fn clears_active_handoff_explicitly() { *state.active_handoff.lock().await = None; assert_eq!(state.active_handoff.lock().await.clone(), None); } + +#[test] +fn uses_quicksilver_alpha_header_for_realtime_v1() { + let headers = + realtime_request_headers(Some("session_1"), Some("sk-test"), RealtimeWsVersion::V1) + .expect("headers") + .expect("headers"); + + assert_eq!( + headers + .get("openai-alpha") + .and_then(|value| value.to_str().ok()), + Some("quicksilver=v1") + ); +} + +#[test] +fn omits_quicksilver_alpha_header_for_realtime_v2() { + let headers = + realtime_request_headers(Some("session_1"), Some("sk-test"), RealtimeWsVersion::V2) + .expect("headers") + .expect("headers"); + + assert!(headers.get("openai-alpha").is_none()); +} diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index b710e095ef..04c086963c 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -72,7 +72,6 @@ use codex_otel::current_span_trace_id; use codex_otel::current_span_w3c_trace_context; use codex_otel::set_parent_from_w3c_trace_context; use codex_protocol::ThreadId; -use codex_protocol::account::PlanType as AccountPlanType; use codex_protocol::approvals::ElicitationRequestEvent; use codex_protocol::approvals::ExecPolicyAmendment; use codex_protocol::approvals::NetworkPolicyAmendment; @@ -80,6 +79,7 @@ use codex_protocol::approvals::NetworkPolicyRuleAction; use codex_protocol::config_types::ApprovalsReviewer; use codex_protocol::config_types::AutoCompactTokenLimitScope; use codex_protocol::config_types::ModeKind; +use codex_protocol::config_types::SERVICE_TIER_DEFAULT_REQUEST_VALUE; use codex_protocol::config_types::Settings; use codex_protocol::config_types::WebSearchMode; use codex_protocol::dynamic_tools::DynamicToolResponse; @@ -320,7 +320,6 @@ use codex_otel::TelemetryAuthMode; use codex_protocol::config_types::CollaborationMode; use codex_protocol::config_types::Personality; use codex_protocol::config_types::ReasoningSummary as ReasoningSummaryConfig; -use codex_protocol::config_types::ServiceTier; use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseInputItem; @@ -589,14 +588,10 @@ impl Codex { developer_instructions: None, }, }; - let account_plan_type = auth_manager - .auth_cached() - .and_then(|auth| auth.account_plan_type()); let service_tier = get_service_tier( config.service_tier.clone(), - config.notices.fast_default_opt_out.unwrap_or(false), - account_plan_type, config.features.enabled(Feature::FastMode), + &model_info, ); let session_configuration = SessionConfiguration { provider: config.model_provider.clone(), @@ -798,17 +793,16 @@ impl Codex { fn get_service_tier( configured_service_tier: Option, - fast_default_opt_out: bool, - account_plan_type: Option, fast_mode_enabled: bool, + model_info: &ModelInfo, ) -> Option { - if configured_service_tier.is_some() || fast_default_opt_out || !fast_mode_enabled { - return configured_service_tier; + if !fast_mode_enabled { + return None; } - - account_plan_type - .is_some_and(is_enterprise_default_service_tier_plan) - .then_some(ServiceTier::Fast.request_value().to_string()) + configured_service_tier.filter(|service_tier| { + service_tier == SERVICE_TIER_DEFAULT_REQUEST_VALUE + || model_info.supports_service_tier(service_tier) + }) } fn session_permission_profile_state_from_config( @@ -817,12 +811,6 @@ fn session_permission_profile_state_from_config( Ok(config.permissions.permission_profile_state().clone()) } -fn is_enterprise_default_service_tier_plan(plan_type: AccountPlanType) -> bool { - plan_type == AccountPlanType::Enterprise - || plan_type.is_business_like() - || plan_type.is_team_like() -} - #[cfg(test)] pub(crate) fn completed_session_loop_termination() -> SessionLoopTermination { futures::future::ready(()).boxed().shared() diff --git a/codex-rs/core/src/session/session.rs b/codex-rs/core/src/session/session.rs index 88958b39ef..791ad7e406 100644 --- a/codex-rs/core/src/session/session.rs +++ b/codex-rs/core/src/session/session.rs @@ -4,6 +4,7 @@ use crate::goals::GoalRuntimeState; use crate::skills::SkillError; use crate::state::ActiveTurn; use codex_protocol::SessionId; +use codex_protocol::config_types::SERVICE_TIER_DEFAULT_REQUEST_VALUE; use codex_protocol::config_types::ServiceTier; use codex_protocol::permissions::FileSystemPath; use codex_protocol::permissions::FileSystemSpecialPath; @@ -222,12 +223,15 @@ impl SessionConfiguration { if let Some(service_tier) = updates.service_tier.clone() { // TODO(aibrahim): Remove once v2 clients no longer send the legacy // "fast" service tier value. - next_configuration.service_tier = service_tier.map(|service_tier| { - ServiceTier::from_request_value(&service_tier) - .map_or(service_tier, |service_tier| { - service_tier.request_value().to_string() - }) - }); + next_configuration.service_tier = match service_tier { + Some(service_tier) => Some( + ServiceTier::from_request_value(&service_tier) + .map_or(service_tier, |service_tier| { + service_tier.request_value().to_string() + }), + ), + None => Some(SERVICE_TIER_DEFAULT_REQUEST_VALUE.to_string()), + }; } if let Some(personality) = updates.personality { next_configuration.personality = Some(personality); diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index a08243701c..316cd4b5a1 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -31,7 +31,7 @@ use codex_models_manager::test_support::get_model_offline_for_tests; use codex_protocol::AgentPath; use codex_protocol::SessionId; use codex_protocol::ThreadId; -use codex_protocol::account::PlanType as AccountPlanType; +use codex_protocol::config_types::SERVICE_TIER_DEFAULT_REQUEST_VALUE; use codex_protocol::config_types::ServiceTier; use codex_protocol::config_types::TrustLevel; use codex_protocol::exec_output::ExecToolCallOutput; @@ -42,6 +42,7 @@ use codex_protocol::models::FunctionCallOutputBody; use codex_protocol::models::FunctionCallOutputPayload; use codex_protocol::models::PermissionProfile; use codex_protocol::models::SandboxEnforcement; +use codex_protocol::openai_models::ModelServiceTier; use codex_protocol::permissions::FileSystemAccessMode; use codex_protocol::permissions::FileSystemPath; use codex_protocol::permissions::FileSystemSandboxEntry; @@ -3381,92 +3382,143 @@ fn session_telemetry( ) } -#[test] -fn get_service_tier_defaults_enterprise_accounts_to_fast() { - assert_eq!( - get_service_tier( - /*configured_service_tier*/ None, - /*fast_default_opt_out*/ false, - Some(AccountPlanType::Enterprise), - /*fast_mode_enabled*/ true, - ), - Some(ServiceTier::Fast.request_value().to_string()) - ); - assert_eq!( - get_service_tier( - /*configured_service_tier*/ None, - /*fast_default_opt_out*/ false, - Some(AccountPlanType::EnterpriseCbpUsageBased), - /*fast_mode_enabled*/ true, - ), - Some(ServiceTier::Fast.request_value().to_string()) - ); - assert_eq!( - get_service_tier( - /*configured_service_tier*/ None, - /*fast_default_opt_out*/ false, - Some(AccountPlanType::Business), - /*fast_mode_enabled*/ true, - ), - Some(ServiceTier::Fast.request_value().to_string()) - ); - assert_eq!( - get_service_tier( - /*configured_service_tier*/ None, - /*fast_default_opt_out*/ false, - Some(AccountPlanType::Team), - /*fast_mode_enabled*/ true, - ), - Some(ServiceTier::Fast.request_value().to_string()) - ); - assert_eq!( - get_service_tier( - /*configured_service_tier*/ None, - /*fast_default_opt_out*/ false, - Some(AccountPlanType::SelfServeBusinessUsageBased), - /*fast_mode_enabled*/ true, - ), - Some(ServiceTier::Fast.request_value().to_string()) - ); +fn model_with_default_service_tier(default_service_tier: Option<&str>) -> ModelInfo { + let mut model_info = model_info::model_info_from_slug("gpt-5.4"); + model_info.service_tiers = vec![ModelServiceTier { + id: ServiceTier::Fast.request_value().to_string(), + name: "Fast".to_string(), + description: "Priority processing.".to_string(), + }]; + model_info.default_service_tier = default_service_tier.map(str::to_string); + model_info } #[test] -fn get_service_tier_respects_fast_default_opt_out() { +fn get_service_tier_does_not_use_model_default_when_absent_and_fast_mode_enabled() { + let model_info = model_with_default_service_tier(Some(ServiceTier::Fast.request_value())); + assert_eq!( get_service_tier( /*configured_service_tier*/ None, - /*fast_default_opt_out*/ true, - Some(AccountPlanType::Enterprise), /*fast_mode_enabled*/ true, + &model_info, ), None ); } #[test] -fn get_service_tier_does_not_default_non_enterprise_or_disabled_fast_mode() { +fn get_service_tier_does_not_use_model_default_when_fast_mode_disabled() { + let model_info = model_with_default_service_tier(Some(ServiceTier::Fast.request_value())); + assert_eq!( get_service_tier( /*configured_service_tier*/ None, - /*fast_default_opt_out*/ false, - Some(AccountPlanType::Pro), - /*fast_mode_enabled*/ true, - ), - None - ); - assert_eq!( - get_service_tier( - /*configured_service_tier*/ None, - /*fast_default_opt_out*/ false, - Some(AccountPlanType::Enterprise), /*fast_mode_enabled*/ false, + &model_info, + ), + None + ); +} + +#[test] +fn get_service_tier_keeps_supported_explicit_tier() { + let model_info = model_with_default_service_tier(Some(ServiceTier::Fast.request_value())); + + assert_eq!( + get_service_tier( + Some(ServiceTier::Fast.request_value().to_string()), + /*fast_mode_enabled*/ true, + &model_info, + ), + Some(ServiceTier::Fast.request_value().to_string()) + ); +} + +#[test] +fn get_service_tier_does_not_default_when_model_has_no_default() { + let model_info = model_with_default_service_tier(/*default_service_tier*/ None); + + assert_eq!( + get_service_tier( + /*configured_service_tier*/ None, + /*fast_mode_enabled*/ true, + &model_info, + ), + None + ); +} + +#[test] +fn get_service_tier_drops_unsupported_configured_tier_when_fast_mode_enabled() { + let model_info = model_with_default_service_tier(Some(ServiceTier::Fast.request_value())); + + assert_eq!( + get_service_tier( + Some("unsupported".to_string()), + /*fast_mode_enabled*/ true, + &model_info, + ), + None + ); + assert_eq!( + get_service_tier( + Some(ServiceTier::Flex.request_value().to_string()), + /*fast_mode_enabled*/ true, + &model_info, + ), + None + ); + assert_eq!( + get_service_tier( + Some(SERVICE_TIER_DEFAULT_REQUEST_VALUE.to_string()), + /*fast_mode_enabled*/ true, + &model_info, + ), + Some(SERVICE_TIER_DEFAULT_REQUEST_VALUE.to_string()) + ); +} + +#[test] +fn get_service_tier_ignores_configured_tier_when_fast_mode_disabled() { + let model_info = model_with_default_service_tier(Some(ServiceTier::Fast.request_value())); + + assert_eq!( + get_service_tier( + Some(ServiceTier::Fast.request_value().to_string()), + /*fast_mode_enabled*/ false, + &model_info, + ), + None + ); + assert_eq!( + get_service_tier( + Some(SERVICE_TIER_DEFAULT_REQUEST_VALUE.to_string()), + /*fast_mode_enabled*/ false, + &model_info, + ), + None + ); + assert_eq!( + get_service_tier( + Some("unsupported".to_string()), + /*fast_mode_enabled*/ false, + &model_info, + ), + None + ); + assert_eq!( + get_service_tier( + /*configured_service_tier*/ None, + /*fast_mode_enabled*/ false, + &model_info, ), None ); } #[tokio::test] -async fn session_settings_null_service_tier_update_clears_service_tier() { +async fn session_settings_null_service_tier_update_uses_default_service_tier() { let session_configuration = make_session_configuration_for_tests().await; let updated = session_configuration @@ -3476,7 +3528,10 @@ async fn session_settings_null_service_tier_update_clears_service_tier() { }) .expect("null service tier update should apply"); - assert_eq!(updated.service_tier, None); + assert_eq!( + updated.service_tier, + Some(SERVICE_TIER_DEFAULT_REQUEST_VALUE.to_string()) + ); } #[tokio::test] diff --git a/codex-rs/core/src/session/turn.rs b/codex-rs/core/src/session/turn.rs index 4ac511f4fa..26ba845460 100644 --- a/codex-rs/core/src/session/turn.rs +++ b/codex-rs/core/src/session/turn.rs @@ -23,7 +23,7 @@ use crate::hook_runtime::record_additional_contexts; use crate::hook_runtime::record_pending_input; use crate::hook_runtime::run_legacy_after_agent_hook; use crate::hook_runtime::run_pending_session_start_hooks; -use crate::hook_runtime::run_stop_hooks; +use crate::hook_runtime::run_turn_stop_hooks; use crate::injection::ToolMentionKind; use crate::injection::app_id_from_path; use crate::injection::tool_kind_for_path; @@ -360,7 +360,7 @@ pub(crate) async fn run_turn( if !needs_follow_up { last_agent_message = sampling_request_last_agent_message; - let stop_outcome = run_stop_hooks( + let stop_outcome = run_turn_stop_hooks( &sess, &turn_context, stop_hook_active, diff --git a/codex-rs/core/src/session/turn_context.rs b/codex-rs/core/src/session/turn_context.rs index 3338d0a558..0d29bc7cdd 100644 --- a/codex-rs/core/src/session/turn_context.rs +++ b/codex-rs/core/src/session/turn_context.rs @@ -473,9 +473,11 @@ impl Session { ); let mut per_turn_config = per_turn_config; - per_turn_config.service_tier = per_turn_config - .service_tier - .filter(|service_tier| model_info.supports_service_tier(service_tier)); + per_turn_config.service_tier = get_service_tier( + per_turn_config.service_tier, + per_turn_config.features.enabled(Feature::FastMode), + &model_info, + ); let per_turn_config = Arc::new(per_turn_config); let turn_metadata_state = Arc::new(TurnMetadataState::new( session_id.to_string(), diff --git a/codex-rs/core/src/tools/handlers/mcp_resource.rs b/codex-rs/core/src/tools/handlers/mcp_resource.rs index 630a1cccb4..9357a9722d 100644 --- a/codex-rs/core/src/tools/handlers/mcp_resource.rs +++ b/codex-rs/core/src/tools/handlers/mcp_resource.rs @@ -202,6 +202,7 @@ async fn emit_tool_call_begin( tool, arguments: arguments.unwrap_or(Value::Null), mcp_app_resource_uri: None, + plugin_id: None, status: McpToolCallStatus::InProgress, result: None, error: None, @@ -240,6 +241,7 @@ async fn emit_tool_call_end( tool, arguments: arguments.unwrap_or(Value::Null), mcp_app_resource_uri: None, + plugin_id: None, status, result, error, diff --git a/codex-rs/core/src/tools/handlers/multi_agents_spec_tests.rs b/codex-rs/core/src/tools/handlers/multi_agents_spec_tests.rs index 6f9eac1fff..d90cdc95e0 100644 --- a/codex-rs/core/src/tools/handlers/multi_agents_spec_tests.rs +++ b/codex-rs/core/src/tools/handlers/multi_agents_spec_tests.rs @@ -26,6 +26,7 @@ fn model_preset(id: &str, show_in_picker: bool) -> ModelPreset { name: "Fast".to_string(), description: "1.5x speed, increased usage".to_string(), }], + default_service_tier: None, is_default: false, upgrade: None, show_in_picker, diff --git a/codex-rs/core/src/unified_exec/process_manager.rs b/codex-rs/core/src/unified_exec/process_manager.rs index 2f5de77319..fb99500755 100644 --- a/codex-rs/core/src/unified_exec/process_manager.rs +++ b/codex-rs/core/src/unified_exec/process_manager.rs @@ -901,8 +901,8 @@ impl UnifiedExecProcessManager { .and_then(|overrides| overrides.write_roots_override.clone()); let spawned = match request.windows_sandbox_level { codex_protocol::config_types::WindowsSandboxLevel::Elevated => { - codex_windows_sandbox::spawn_windows_sandbox_session_elevated( - policy_json.as_str(), + codex_windows_sandbox::spawn_windows_sandbox_session_elevated_for_permission_profile( + &request.permission_profile, request.windows_sandbox_policy_cwd.as_path(), codex_home.as_ref(), request.command.clone(), diff --git a/codex-rs/core/tests/common/test_codex.rs b/codex-rs/core/tests/common/test_codex.rs index 5f5c7ee85a..a398758291 100644 --- a/codex-rs/core/tests/common/test_codex.rs +++ b/codex-rs/core/tests/common/test_codex.rs @@ -28,7 +28,6 @@ use codex_login::CodexAuth; use codex_model_provider_info::ModelProviderInfo; use codex_model_provider_info::built_in_model_providers; use codex_models_manager::bundled_models_response; -use codex_protocol::config_types::ServiceTier; use codex_protocol::models::PermissionProfile; use codex_protocol::openai_models::ModelsResponse; use codex_protocol::protocol::AskForApproval; @@ -667,13 +666,13 @@ impl TestCodex { pub async fn submit_turn_with_service_tier( &self, prompt: &str, - service_tier: Option, + service_tier: Option<&str>, ) -> Result<()> { self.submit_turn_with_permission_profile_context( prompt, AskForApproval::Never, PermissionProfile::Disabled, - Some(service_tier.map(|service_tier| service_tier.request_value().to_string())), + Some(service_tier.map(str::to_string)), /*environments*/ None, ) .await diff --git a/codex-rs/core/tests/suite/agent_websocket.rs b/codex-rs/core/tests/suite/agent_websocket.rs index 6e985eebe0..6fe697d2b1 100644 --- a/codex-rs/core/tests/suite/agent_websocket.rs +++ b/codex-rs/core/tests/suite/agent_websocket.rs @@ -269,7 +269,7 @@ async fn websocket_v2_first_turn_uses_updated_fast_tier_after_startup_prewarm() assert_eq!(warmup["generate"].as_bool(), Some(false)); assert_eq!(warmup.get("service_tier"), None); - test.submit_turn_with_service_tier("hello", Some(ServiceTier::Fast)) + test.submit_turn_with_service_tier("hello", Some(ServiceTier::Fast.request_value())) .await?; assert_eq!(server.handshakes().len(), 1); @@ -385,7 +385,7 @@ async fn websocket_v2_next_turn_uses_updated_service_tier() -> Result<()> { assert_eq!(warmup["generate"].as_bool(), Some(false)); assert_eq!(warmup.get("service_tier"), None); - test.submit_turn_with_service_tier("first", Some(ServiceTier::Fast)) + test.submit_turn_with_service_tier("first", Some(ServiceTier::Fast.request_value())) .await?; test.submit_turn_with_service_tier("second", /*service_tier*/ None) .await?; diff --git a/codex-rs/core/tests/suite/model_switching.rs b/codex-rs/core/tests/suite/model_switching.rs index 009dfda60f..7e77fb79d3 100644 --- a/codex-rs/core/tests/suite/model_switching.rs +++ b/codex-rs/core/tests/suite/model_switching.rs @@ -4,6 +4,7 @@ use codex_features::Feature; use codex_login::CodexAuth; use codex_models_manager::manager::RefreshStrategy; use codex_protocol::config_types::ReasoningSummary; +use codex_protocol::config_types::SERVICE_TIER_DEFAULT_REQUEST_VALUE; use codex_protocol::config_types::ServiceTier; use codex_protocol::models::PermissionProfile; use codex_protocol::openai_models::ConfigShellToolType; @@ -113,6 +114,7 @@ fn test_model_info( priority: 1, additional_speed_tiers: Vec::new(), service_tiers: Vec::new(), + default_service_tier: None, upgrade: None, base_instructions: "base instructions".to_string(), model_messages: None, @@ -289,7 +291,7 @@ async fn service_tier_change_is_applied_on_next_http_turn() -> Result<()> { let test = test_codex().build(&server).await?; - test.submit_turn_with_service_tier("fast turn", Some(ServiceTier::Fast)) + test.submit_turn_with_service_tier("fast turn", Some(ServiceTier::Fast.request_value())) .await?; test.submit_turn_with_service_tier("standard turn", /*service_tier*/ None) .await?; @@ -334,7 +336,7 @@ async fn flex_service_tier_is_applied_to_http_turn() -> Result<()> { }); let test = builder.build(&server).await?; - test.submit_turn_with_service_tier("flex turn", Some(ServiceTier::Flex)) + test.submit_turn_with_service_tier("flex turn", Some(ServiceTier::Flex.request_value())) .await?; let request = resp_mock.single_request(); @@ -367,7 +369,85 @@ async fn unsupported_service_tier_is_omitted_from_http_turn() -> Result<()> { }); let test = builder.build(&server).await?; - test.submit_turn_with_service_tier("fast turn", Some(ServiceTier::Fast)) + test.submit_turn_with_service_tier("fast turn", Some(ServiceTier::Fast.request_value())) + .await?; + + let request = resp_mock.single_request(); + let body = request.body_json(); + assert_eq!(body.get("service_tier"), None); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn default_service_tier_override_is_omitted_from_http_turn() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let model_slug = "test-default-tier-model"; + let mut model = test_model_info( + model_slug, + model_slug, + "has catalog default service tier", + default_input_modalities(), + ); + model.service_tiers = vec![ModelServiceTier { + id: ServiceTier::Fast.request_value().to_string(), + name: "fast".to_string(), + description: "Fast processing.".to_string(), + }]; + model.default_service_tier = Some(ServiceTier::Fast.request_value().to_string()); + let resp_mock = mount_sse_once(&server, sse_completed("resp-1")).await; + + let mut builder = test_codex() + .with_model(model_slug) + .with_config(move |config| { + config.model_catalog = Some(ModelsResponse { + models: vec![model], + }); + }); + let test = builder.build(&server).await?; + + test.submit_turn_with_service_tier("default turn", Some(SERVICE_TIER_DEFAULT_REQUEST_VALUE)) + .await?; + + let request = resp_mock.single_request(); + let body = request.body_json(); + assert_eq!(body.get("service_tier"), None); + + Ok(()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn null_service_tier_override_is_omitted_from_http_turn_with_catalog_default() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let model_slug = "test-null-default-tier-model"; + let mut model = test_model_info( + model_slug, + model_slug, + "has catalog default service tier", + default_input_modalities(), + ); + model.service_tiers = vec![ModelServiceTier { + id: ServiceTier::Fast.request_value().to_string(), + name: "fast".to_string(), + description: "Fast processing.".to_string(), + }]; + model.default_service_tier = Some(ServiceTier::Fast.request_value().to_string()); + let resp_mock = mount_sse_once(&server, sse_completed("resp-1")).await; + + let mut builder = test_codex() + .with_model(model_slug) + .with_config(move |config| { + config.model_catalog = Some(ModelsResponse { + models: vec![model], + }); + }); + let test = builder.build(&server).await?; + + test.submit_turn_with_service_tier("standard turn", /*service_tier*/ None) .await?; let request = resp_mock.single_request(); @@ -864,6 +944,7 @@ async fn model_switch_to_smaller_model_updates_token_context_window() -> Result< priority: 1, additional_speed_tiers: Vec::new(), service_tiers: Vec::new(), + default_service_tier: None, upgrade: None, base_instructions: "base instructions".to_string(), model_messages: None, diff --git a/codex-rs/core/tests/suite/models_cache_ttl.rs b/codex-rs/core/tests/suite/models_cache_ttl.rs index 3b729738df..6d11b47cba 100644 --- a/codex-rs/core/tests/suite/models_cache_ttl.rs +++ b/codex-rs/core/tests/suite/models_cache_ttl.rs @@ -347,6 +347,7 @@ fn test_remote_model(slug: &str, priority: i32) -> ModelInfo { priority, additional_speed_tiers: Vec::new(), service_tiers: Vec::new(), + default_service_tier: None, upgrade: None, base_instructions: "base instructions".to_string(), model_messages: None, diff --git a/codex-rs/core/tests/suite/personality.rs b/codex-rs/core/tests/suite/personality.rs index bbe8178f8d..96695769c9 100644 --- a/codex-rs/core/tests/suite/personality.rs +++ b/codex-rs/core/tests/suite/personality.rs @@ -562,6 +562,7 @@ async fn remote_model_friendly_personality_instructions_with_feature() -> anyhow priority: 1, additional_speed_tiers: Vec::new(), service_tiers: Vec::new(), + default_service_tier: None, upgrade: None, base_instructions: "base instructions".to_string(), model_messages: Some(ModelMessages { @@ -671,6 +672,7 @@ async fn user_turn_personality_remote_model_template_includes_update_message() - priority: 1, additional_speed_tiers: Vec::new(), service_tiers: Vec::new(), + default_service_tier: None, upgrade: None, base_instructions: "base instructions".to_string(), model_messages: Some(ModelMessages { diff --git a/codex-rs/core/tests/suite/prompt_caching.rs b/codex-rs/core/tests/suite/prompt_caching.rs index a4b337f059..4ce137a557 100644 --- a/codex-rs/core/tests/suite/prompt_caching.rs +++ b/codex-rs/core/tests/suite/prompt_caching.rs @@ -179,6 +179,9 @@ async fn prompt_tools_are_consistent_across_requests() -> anyhow::Result<()> { }; expected_tools_names.extend([ "update_plan", + "get_goal", + "create_goal", + "update_goal", "request_user_input", "apply_patch", "view_image", diff --git a/codex-rs/core/tests/suite/remote_models.rs b/codex-rs/core/tests/suite/remote_models.rs index e143cb8e3e..18ebd732b7 100644 --- a/codex-rs/core/tests/suite/remote_models.rs +++ b/codex-rs/core/tests/suite/remote_models.rs @@ -475,6 +475,7 @@ async fn remote_models_remote_model_uses_unified_exec() -> Result<()> { priority: 1, additional_speed_tiers: Vec::new(), service_tiers: Vec::new(), + default_service_tier: None, upgrade: None, base_instructions: "base instructions".to_string(), model_messages: None, @@ -722,6 +723,7 @@ async fn remote_models_apply_remote_base_instructions() -> Result<()> { priority: 1, additional_speed_tiers: Vec::new(), service_tiers: Vec::new(), + default_service_tier: None, upgrade: None, base_instructions: remote_base.to_string(), model_messages: None, @@ -1203,6 +1205,7 @@ fn test_remote_model_with_policy( priority, additional_speed_tiers: Vec::new(), service_tiers: Vec::new(), + default_service_tier: None, upgrade: None, base_instructions: "base instructions".to_string(), model_messages: None, diff --git a/codex-rs/core/tests/suite/rmcp_client.rs b/codex-rs/core/tests/suite/rmcp_client.rs index 210c287c2f..8e85c5d5ee 100644 --- a/codex-rs/core/tests/suite/rmcp_client.rs +++ b/codex-rs/core/tests/suite/rmcp_client.rs @@ -1103,6 +1103,7 @@ async fn stdio_image_responses_round_trip() -> anyhow::Result<()> { arguments: Some(json!({})), }, mcp_app_resource_uri: None, + plugin_id: None, }, ); @@ -1275,6 +1276,7 @@ async fn stdio_image_responses_are_sanitized_for_text_only_model() -> anyhow::Re priority: 1, additional_speed_tiers: Vec::new(), service_tiers: Vec::new(), + default_service_tier: None, upgrade: None, base_instructions: "base instructions".to_string(), model_messages: None, diff --git a/codex-rs/core/tests/suite/spawn_agent_description.rs b/codex-rs/core/tests/suite/spawn_agent_description.rs index 9a7d70adeb..fbeb90fba5 100644 --- a/codex-rs/core/tests/suite/spawn_agent_description.rs +++ b/codex-rs/core/tests/suite/spawn_agent_description.rs @@ -63,6 +63,7 @@ fn test_model_info( priority: 1, additional_speed_tiers: Vec::new(), service_tiers, + default_service_tier: None, upgrade: None, base_instructions: "base instructions".to_string(), model_messages: None, diff --git a/codex-rs/core/tests/suite/subagent_notifications.rs b/codex-rs/core/tests/suite/subagent_notifications.rs index 25d16faa51..087e966588 100644 --- a/codex-rs/core/tests/suite/subagent_notifications.rs +++ b/codex-rs/core/tests/suite/subagent_notifications.rs @@ -1,9 +1,19 @@ use anyhow::Result; +use codex_core::StartThreadOptions; use codex_core::ThreadConfigSnapshot; use codex_core::config::AgentRoleConfig; use codex_features::Feature; use codex_protocol::ThreadId; +use codex_protocol::models::PermissionProfile; use codex_protocol::openai_models::ReasoningEffort; +use codex_protocol::protocol::AskForApproval; +use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::InitialHistory; +use codex_protocol::protocol::Op; +use codex_protocol::protocol::SessionSource; +use codex_protocol::protocol::SubAgentSource; +use codex_protocol::user_input::UserInput; +use core_test_support::hooks::trust_discovered_hooks; use core_test_support::responses::ResponsesRequest; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; @@ -20,6 +30,8 @@ use core_test_support::responses::start_mock_server; use core_test_support::skip_if_no_network; use core_test_support::test_codex::TestCodex; use core_test_support::test_codex::test_codex; +use core_test_support::test_codex::turn_permission_fields; +use core_test_support::wait_for_event_match; use pretty_assertions::assert_eq; use serde_json::Value; use serde_json::json; @@ -43,6 +55,8 @@ const REQUESTED_REASONING_EFFORT: ReasoningEffort = ReasoningEffort::Low; const ROLE_MODEL: &str = "gpt-5.4"; const ROLE_REASONING_EFFORT: ReasoningEffort = ReasoningEffort::High; const SUBAGENT_START_CONTEXT: &str = "subagent start context reaches child"; +const SUBAGENT_STOP_CONTINUATION: &str = "continue only the child"; +const INTERNAL_SUBAGENT_PROMPT: &str = "internal subagent: review"; fn body_contains(req: &wiremock::Request, text: &str) -> bool { let is_zstd = req @@ -101,7 +115,11 @@ fn write_home_skill(codex_home: &Path, dir: &str, name: &str, description: &str) Ok(()) } -fn write_subagent_start_hooks(home: &Path) -> Result<()> { +fn write_subagent_lifecycle_hooks( + home: &Path, + stop_prompts: &[&str], + subagent_stop_matcher: &str, +) -> Result<()> { let session_start_script_path = home.join("session_start_hook.py"); let session_start_log_path = home.join("session_start_hook_log.jsonl"); let session_start_script = format!( @@ -133,6 +151,51 @@ print(json.dumps({{"hookSpecificOutput": {{"hookEventName": "SubagentStart", "ad start_log_path = start_log_path.display(), ); + let subagent_stop_script_path = home.join("subagent_stop_hook.py"); + let subagent_stop_log_path = home.join("subagent_stop_hook_log.jsonl"); + let prompts_json = serde_json::to_string(stop_prompts)?; + let subagent_stop_script = format!( + r#"import json +from pathlib import Path +import sys + +log_path = Path(r"{subagent_stop_log_path}") +block_prompts = {prompts_json} + +payload = json.load(sys.stdin) +existing = [] +if log_path.exists(): + existing = [line for line in log_path.read_text(encoding="utf-8").splitlines() if line.strip()] + +with log_path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(payload) + "\n") + +invocation_index = len(existing) +if invocation_index < len(block_prompts): + print(json.dumps({{"decision": "block", "reason": block_prompts[invocation_index]}})) +else: + print(json.dumps({{"systemMessage": f"subagent stop pass {{invocation_index + 1}} complete"}})) +"#, + subagent_stop_log_path = subagent_stop_log_path.display(), + prompts_json = prompts_json, + ); + + let stop_script_path = home.join("stop_hook.py"); + let stop_log_path = home.join("stop_hook_log.jsonl"); + let stop_script = format!( + r#"import json +from pathlib import Path +import sys + +log_path = Path(r"{stop_log_path}") +payload = json.load(sys.stdin) +with log_path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(payload) + "\n") +print(json.dumps({{"systemMessage": "root stop complete"}})) +"#, + stop_log_path = stop_log_path.display(), + ); + let hooks = serde_json::json!({ "hooks": { "SessionStart": [{ @@ -148,12 +211,27 @@ print(json.dumps({{"hookSpecificOutput": {{"hookEventName": "SubagentStart", "ad "type": "command", "command": format!("python3 {}", start_script_path.display()), }] + }], + "SubagentStop": [{ + "matcher": subagent_stop_matcher, + "hooks": [{ + "type": "command", + "command": format!("python3 {}", subagent_stop_script_path.display()), + }] + }], + "Stop": [{ + "hooks": [{ + "type": "command", + "command": format!("python3 {}", stop_script_path.display()), + }] }] } }); fs::write(&session_start_script_path, session_start_script)?; fs::write(&start_script_path, start_script)?; + fs::write(&subagent_stop_script_path, subagent_stop_script)?; + fs::write(&stop_script_path, stop_script)?; fs::write(home.join("hooks.json"), hooks.to_string())?; Ok(()) } @@ -426,12 +504,12 @@ async fn subagent_start_replaces_session_start_and_injects_context() -> Result<( let test = test_codex() .with_pre_build_hook(|home| { - if let Err(error) = write_subagent_start_hooks(home) { + if let Err(error) = write_subagent_lifecycle_hooks(home, &[], "worker") { panic!("failed to write subagent hook fixture: {error}"); } }) .with_config(|config| { - core_test_support::hooks::trust_discovered_hooks(config); + trust_discovered_hooks(config); config .features .enable(Feature::Collab) @@ -474,6 +552,210 @@ async fn subagent_start_replaces_session_start_and_injects_context() -> Result<( Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn subagent_stop_replaces_stop_and_skips_internal_subagents() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let spawn_args = serde_json::to_string(&json!({ + "message": CHILD_PROMPT, + "task_name": "child", + "agent_type": "worker", + }))?; + + mount_sse_once_match( + &server, + |req: &wiremock::Request| body_contains(req, TURN_1_PROMPT), + sse(vec![ + ev_response_created("resp-turn1-1"), + ev_function_call_with_namespace( + SPAWN_CALL_ID, + MULTI_AGENT_V1_NAMESPACE, + "spawn_agent", + &spawn_args, + ), + ev_completed("resp-turn1-1"), + ]), + ) + .await; + + let first_child_request = mount_sse_once_match( + &server, + |req: &wiremock::Request| { + body_contains(req, CHILD_PROMPT) && !body_contains(req, SPAWN_CALL_ID) + }, + sse(vec![ + ev_response_created("resp-child-1"), + ev_assistant_message("msg-child-1", "child done first"), + ev_completed("resp-child-1"), + ]), + ) + .await; + let second_child_request = mount_sse_once_match( + &server, + |req: &wiremock::Request| { + body_contains(req, SUBAGENT_STOP_CONTINUATION) && !body_contains(req, SPAWN_CALL_ID) + }, + sse(vec![ + ev_response_created("resp-child-2"), + ev_assistant_message("msg-child-2", "child done final"), + ev_completed("resp-child-2"), + ]), + ) + .await; + + let _turn1_followup = mount_sse_once_match( + &server, + |req: &wiremock::Request| body_contains(req, SPAWN_CALL_ID), + sse(vec![ + ev_response_created("resp-turn1-2"), + ev_assistant_message("msg-turn1-2", "parent done"), + ev_completed("resp-turn1-2"), + ]), + ) + .await; + let internal_request = mount_sse_once_match( + &server, + |req: &wiremock::Request| body_contains(req, INTERNAL_SUBAGENT_PROMPT), + sse(vec![ + ev_response_created("resp-internal-1"), + ev_assistant_message("msg-internal-1", "internal subagent done"), + ev_completed("resp-internal-1"), + ]), + ) + .await; + + let test = test_codex() + .with_pre_build_hook(|home| { + if let Err(error) = + write_subagent_lifecycle_hooks(home, &[SUBAGENT_STOP_CONTINUATION], "") + { + panic!("failed to write subagent hook fixture: {error}"); + } + }) + .with_config(|config| { + trust_discovered_hooks(config); + config + .features + .enable(Feature::Collab) + .expect("test config should allow feature update"); + }) + .build(&server) + .await?; + + test.submit_turn(TURN_1_PROMPT).await?; + let _ = wait_for_requests(&first_child_request).await?; + let _ = wait_for_requests(&second_child_request).await?; + + let subagent_stop_inputs = wait_for_hook_log( + test.codex_home_path(), + "subagent_stop_hook_log.jsonl", + /*expected_len*/ 2, + ) + .await?; + assert_eq!(subagent_stop_inputs.len(), 2); + assert_eq!( + subagent_stop_inputs + .iter() + .map(|input| input["stop_hook_active"].as_bool()) + .collect::>(), + vec![Some(false), Some(true)] + ); + assert_eq!( + subagent_stop_inputs[0]["agent_type"].as_str(), + Some("worker") + ); + let parent_transcript_path = subagent_stop_inputs[0]["transcript_path"] + .as_str() + .expect("SubagentStop should include parent transcript_path"); + let agent_transcript_path = subagent_stop_inputs[0]["agent_transcript_path"] + .as_str() + .expect("SubagentStop should include agent_transcript_path"); + assert_ne!(parent_transcript_path, agent_transcript_path); + assert_eq!( + subagent_stop_inputs[1]["transcript_path"].as_str(), + Some(parent_transcript_path) + ); + assert_eq!( + subagent_stop_inputs[1]["agent_transcript_path"].as_str(), + Some(agent_transcript_path) + ); + assert_eq!( + subagent_stop_inputs[0]["last_assistant_message"].as_str(), + Some("child done first") + ); + + let stop_inputs = read_hook_log(test.codex_home_path(), "stop_hook_log.jsonl")?; + assert!( + stop_inputs + .iter() + .all(|input| input["last_assistant_message"].as_str() != Some("child done first")), + "child completion should not invoke the normal Stop hook" + ); + let stop_input_count = stop_inputs.len(); + + // This matcher would catch the old synthetic "review" SubagentStop target + // because the SubagentStop hook above intentionally matches all agent types. + let internal_thread = test + .thread_manager + .start_thread_with_options(StartThreadOptions { + config: test.config.clone(), + initial_history: InitialHistory::New, + session_source: Some(SessionSource::SubAgent(SubAgentSource::Review)), + thread_source: None, + dynamic_tools: Vec::new(), + persist_extended_history: false, + metrics_service_name: None, + parent_trace: None, + environments: Vec::new(), + }) + .await?; + + let (sandbox_policy, permission_profile) = + turn_permission_fields(PermissionProfile::Disabled, test.cwd_path()); + internal_thread + .thread + .submit(Op::UserInput { + items: vec![UserInput::Text { + text: INTERNAL_SUBAGENT_PROMPT.to_string(), + text_elements: Vec::new(), + }], + environments: None, + final_output_json_schema: None, + responsesapi_client_metadata: None, + thread_settings: codex_protocol::protocol::ThreadSettingsOverrides { + cwd: Some(test.config.cwd.to_path_buf()), + approval_policy: Some(AskForApproval::Never), + sandbox_policy: Some(sandbox_policy), + permission_profile, + model: Some(internal_thread.session_configured.model.clone()), + ..Default::default() + }, + }) + .await?; + let turn_id = wait_for_event_match(internal_thread.thread.as_ref(), |event| match event { + EventMsg::TurnStarted(event) => Some(event.turn_id.clone()), + _ => None, + }) + .await; + wait_for_event_match(internal_thread.thread.as_ref(), |event| match event { + EventMsg::TurnComplete(event) if event.turn_id == turn_id => Some(()), + _ => None, + }) + .await; + let requests = wait_for_requests(&internal_request).await?; + assert_eq!(requests.len(), 1); + + let subagent_stop_inputs_after_internal = + read_hook_log(test.codex_home_path(), "subagent_stop_hook_log.jsonl")?; + assert_eq!(subagent_stop_inputs_after_internal, subagent_stop_inputs); + + let stop_inputs_after_internal = read_hook_log(test.codex_home_path(), "stop_hook_log.jsonl")?; + assert_eq!(stop_inputs_after_internal.len(), stop_input_count); + + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn subagent_notification_is_included_without_wait() -> Result<()> { skip_if_no_network!(Ok(())); diff --git a/codex-rs/core/tests/suite/view_image.rs b/codex-rs/core/tests/suite/view_image.rs index 6306b88b8f..867ba10858 100644 --- a/codex-rs/core/tests/suite/view_image.rs +++ b/codex-rs/core/tests/suite/view_image.rs @@ -1357,6 +1357,7 @@ async fn view_image_tool_returns_unsupported_message_for_text_only_model() -> an priority: 1, additional_speed_tiers: Vec::new(), service_tiers: Vec::new(), + default_service_tier: None, upgrade: None, base_instructions: "base instructions".to_string(), model_messages: None, diff --git a/codex-rs/exec/src/event_processor_with_jsonl_output_tests.rs b/codex-rs/exec/src/event_processor_with_jsonl_output_tests.rs index 6bd358f6be..b8b0267fc4 100644 --- a/codex-rs/exec/src/event_processor_with_jsonl_output_tests.rs +++ b/codex-rs/exec/src/event_processor_with_jsonl_output_tests.rs @@ -72,6 +72,7 @@ fn mcp_tool_call_result_preserves_meta_in_jsonl_event() { status: McpToolCallStatus::Completed, arguments: json!({"search_query": [{"q": "OpenAI Codex CLI documentation"}]}), mcp_app_resource_uri: None, + plugin_id: None, result: Some(Box::new(codex_app_server_protocol::McpToolCallResult { content: vec![json!({"type": "text", "text": "search result"})], structured_content: None, diff --git a/codex-rs/exec/tests/event_processor_with_json_output.rs b/codex-rs/exec/tests/event_processor_with_json_output.rs index acbac8254c..ff97b6832c 100644 --- a/codex-rs/exec/tests/event_processor_with_json_output.rs +++ b/codex-rs/exec/tests/event_processor_with_json_output.rs @@ -478,6 +478,7 @@ fn mcp_tool_call_begin_and_end_emit_item_events() { status: ApiMcpToolCallStatus::InProgress, arguments: json!({ "key": "value" }), mcp_app_resource_uri: None, + plugin_id: None, result: None, error: None, duration_ms: None, @@ -495,6 +496,7 @@ fn mcp_tool_call_begin_and_end_emit_item_events() { status: ApiMcpToolCallStatus::Completed, arguments: json!({ "key": "value" }), mcp_app_resource_uri: None, + plugin_id: None, result: Some(Box::new(McpToolCallResult { content: Vec::new(), structured_content: None, @@ -566,6 +568,7 @@ fn mcp_tool_call_failure_sets_failed_status() { status: ApiMcpToolCallStatus::Failed, arguments: json!({ "param": 42 }), mcp_app_resource_uri: None, + plugin_id: None, result: None, error: Some(McpToolCallError { message: "tool exploded".to_string(), @@ -614,6 +617,7 @@ fn mcp_tool_call_defaults_arguments_and_preserves_structured_content() { status: ApiMcpToolCallStatus::InProgress, arguments: serde_json::Value::Null, mcp_app_resource_uri: None, + plugin_id: None, result: None, error: None, duration_ms: None, @@ -631,6 +635,7 @@ fn mcp_tool_call_defaults_arguments_and_preserves_structured_content() { status: ApiMcpToolCallStatus::Completed, arguments: serde_json::Value::Null, mcp_app_resource_uri: None, + plugin_id: None, result: Some(Box::new(McpToolCallResult { content: vec![json!({ "type": "text", diff --git a/codex-rs/features/src/lib.rs b/codex-rs/features/src/lib.rs index c20fa8683a..662d01fe26 100644 --- a/codex-rs/features/src/lib.rs +++ b/codex-rs/features/src/lib.rs @@ -1077,12 +1077,8 @@ pub const FEATURES: &[FeatureSpec] = &[ FeatureSpec { id: Feature::Goals, key: "goals", - stage: Stage::Experimental { - name: "Goals", - menu_description: "Set a persistent goal Codex can continue over time", - announcement: "", - }, - default_enabled: false, + stage: Stage::Stable, + default_enabled: true, }, FeatureSpec { id: Feature::CollaborationModes, diff --git a/codex-rs/hooks/schema/generated/permission-request.command.output.schema.json b/codex-rs/hooks/schema/generated/permission-request.command.output.schema.json index 44e775a03d..7d63b56c96 100644 --- a/codex-rs/hooks/schema/generated/permission-request.command.output.schema.json +++ b/codex-rs/hooks/schema/generated/permission-request.command.output.schema.json @@ -12,6 +12,7 @@ "SessionStart", "UserPromptSubmit", "SubagentStart", + "SubagentStop", "Stop" ], "type": "string" diff --git a/codex-rs/hooks/schema/generated/post-tool-use.command.output.schema.json b/codex-rs/hooks/schema/generated/post-tool-use.command.output.schema.json index b762c549c5..964c3ba624 100644 --- a/codex-rs/hooks/schema/generated/post-tool-use.command.output.schema.json +++ b/codex-rs/hooks/schema/generated/post-tool-use.command.output.schema.json @@ -18,6 +18,7 @@ "SessionStart", "UserPromptSubmit", "SubagentStart", + "SubagentStop", "Stop" ], "type": "string" diff --git a/codex-rs/hooks/schema/generated/pre-tool-use.command.output.schema.json b/codex-rs/hooks/schema/generated/pre-tool-use.command.output.schema.json index c4c4132448..a74abd14e8 100644 --- a/codex-rs/hooks/schema/generated/pre-tool-use.command.output.schema.json +++ b/codex-rs/hooks/schema/generated/pre-tool-use.command.output.schema.json @@ -12,6 +12,7 @@ "SessionStart", "UserPromptSubmit", "SubagentStart", + "SubagentStop", "Stop" ], "type": "string" diff --git a/codex-rs/hooks/schema/generated/session-start.command.output.schema.json b/codex-rs/hooks/schema/generated/session-start.command.output.schema.json index d8a0f46482..e1abb88a52 100644 --- a/codex-rs/hooks/schema/generated/session-start.command.output.schema.json +++ b/codex-rs/hooks/schema/generated/session-start.command.output.schema.json @@ -12,6 +12,7 @@ "SessionStart", "UserPromptSubmit", "SubagentStart", + "SubagentStop", "Stop" ], "type": "string" diff --git a/codex-rs/hooks/schema/generated/subagent-start.command.output.schema.json b/codex-rs/hooks/schema/generated/subagent-start.command.output.schema.json index 16140f326b..4e645bb918 100644 --- a/codex-rs/hooks/schema/generated/subagent-start.command.output.schema.json +++ b/codex-rs/hooks/schema/generated/subagent-start.command.output.schema.json @@ -12,6 +12,7 @@ "SessionStart", "UserPromptSubmit", "SubagentStart", + "SubagentStop", "Stop" ], "type": "string" diff --git a/codex-rs/hooks/schema/generated/subagent-stop.command.input.schema.json b/codex-rs/hooks/schema/generated/subagent-stop.command.input.schema.json new file mode 100644 index 0000000000..19646db1d2 --- /dev/null +++ b/codex-rs/hooks/schema/generated/subagent-stop.command.input.schema.json @@ -0,0 +1,75 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "additionalProperties": false, + "definitions": { + "NullableString": { + "type": [ + "string", + "null" + ] + } + }, + "properties": { + "agent_id": { + "type": "string" + }, + "agent_transcript_path": { + "$ref": "#/definitions/NullableString" + }, + "agent_type": { + "type": "string" + }, + "cwd": { + "type": "string" + }, + "hook_event_name": { + "const": "SubagentStop", + "type": "string" + }, + "last_assistant_message": { + "$ref": "#/definitions/NullableString" + }, + "model": { + "type": "string" + }, + "permission_mode": { + "enum": [ + "default", + "acceptEdits", + "plan", + "dontAsk", + "bypassPermissions" + ], + "type": "string" + }, + "session_id": { + "type": "string" + }, + "stop_hook_active": { + "type": "boolean" + }, + "transcript_path": { + "$ref": "#/definitions/NullableString" + }, + "turn_id": { + "description": "Codex extension: expose the active turn id to internal turn-scoped hooks.", + "type": "string" + } + }, + "required": [ + "agent_id", + "agent_transcript_path", + "agent_type", + "cwd", + "hook_event_name", + "last_assistant_message", + "model", + "permission_mode", + "session_id", + "stop_hook_active", + "transcript_path", + "turn_id" + ], + "title": "subagent-stop.command.input", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/hooks/schema/generated/subagent-stop.command.output.schema.json b/codex-rs/hooks/schema/generated/subagent-stop.command.output.schema.json new file mode 100644 index 0000000000..0cb1dd2a57 --- /dev/null +++ b/codex-rs/hooks/schema/generated/subagent-stop.command.output.schema.json @@ -0,0 +1,45 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "additionalProperties": false, + "definitions": { + "BlockDecisionWire": { + "enum": [ + "block" + ], + "type": "string" + } + }, + "properties": { + "continue": { + "default": true, + "type": "boolean" + }, + "decision": { + "allOf": [ + { + "$ref": "#/definitions/BlockDecisionWire" + } + ], + "default": null + }, + "reason": { + "default": null, + "description": "Claude requires `reason` when `decision` is `block`; we enforce that semantic rule during output parsing rather than in the JSON schema.", + "type": "string" + }, + "stopReason": { + "default": null, + "type": "string" + }, + "suppressOutput": { + "default": false, + "type": "boolean" + }, + "systemMessage": { + "default": null, + "type": "string" + } + }, + "title": "subagent-stop.command.output", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/hooks/schema/generated/user-prompt-submit.command.output.schema.json b/codex-rs/hooks/schema/generated/user-prompt-submit.command.output.schema.json index d4d66d2976..61c530ce04 100644 --- a/codex-rs/hooks/schema/generated/user-prompt-submit.command.output.schema.json +++ b/codex-rs/hooks/schema/generated/user-prompt-submit.command.output.schema.json @@ -18,6 +18,7 @@ "SessionStart", "UserPromptSubmit", "SubagentStart", + "SubagentStop", "Stop" ], "type": "string" diff --git a/codex-rs/hooks/src/engine/dispatcher.rs b/codex-rs/hooks/src/engine/dispatcher.rs index 51c6d6672e..50822bfc96 100644 --- a/codex-rs/hooks/src/engine/dispatcher.rs +++ b/codex-rs/hooks/src/engine/dispatcher.rs @@ -50,6 +50,7 @@ pub(crate) fn select_handlers_for_matcher_inputs( | HookEventName::PostToolUse | HookEventName::SessionStart | HookEventName::SubagentStart + | HookEventName::SubagentStop | HookEventName::PreCompact | HookEventName::PostCompact => { if matcher_inputs.is_empty() { @@ -147,6 +148,7 @@ fn scope_for_event(event_name: HookEventName) -> HookScope { | HookEventName::PreCompact | HookEventName::PostCompact | HookEventName::UserPromptSubmit + | HookEventName::SubagentStop | HookEventName::Stop => HookScope::Turn, } } diff --git a/codex-rs/hooks/src/engine/mod.rs b/codex-rs/hooks/src/engine/mod.rs index 7cbbd7a027..859fc54069 100644 --- a/codex-rs/hooks/src/engine/mod.rs +++ b/codex-rs/hooks/src/engine/mod.rs @@ -71,6 +71,7 @@ impl ConfiguredHandler { codex_protocol::protocol::HookEventName::SessionStart => "session-start", codex_protocol::protocol::HookEventName::UserPromptSubmit => "user-prompt-submit", codex_protocol::protocol::HookEventName::SubagentStart => "subagent-start", + codex_protocol::protocol::HookEventName::SubagentStop => "subagent-stop", codex_protocol::protocol::HookEventName::Stop => "stop", } } diff --git a/codex-rs/hooks/src/engine/output_parser.rs b/codex-rs/hooks/src/engine/output_parser.rs index 1ea44c0903..11b44395c8 100644 --- a/codex-rs/hooks/src/engine/output_parser.rs +++ b/codex-rs/hooks/src/engine/output_parser.rs @@ -87,6 +87,7 @@ use crate::schema::PreToolUsePermissionDecisionWire; use crate::schema::SessionStartCommandOutputWire; use crate::schema::StopCommandOutputWire; use crate::schema::SubagentStartCommandOutputWire; +use crate::schema::SubagentStopCommandOutputWire; use crate::schema::UserPromptSubmitCommandOutputWire; pub(crate) fn parse_session_start(stdout: &str) -> Option { @@ -280,22 +281,46 @@ pub(crate) fn parse_user_prompt_submit(stdout: &str) -> Option Option { let wire: StopCommandOutputWire = parse_json(stdout)?; - let should_block = matches!(wire.decision, Some(BlockDecisionWire::Block)); + Some(stop_output( + wire.universal, + wire.decision, + wire.reason, + "Stop", + )) +} + +pub(crate) fn parse_subagent_stop(stdout: &str) -> Option { + let wire: SubagentStopCommandOutputWire = parse_json(stdout)?; + Some(stop_output( + wire.universal, + wire.decision, + wire.reason, + "SubagentStop", + )) +} + +fn stop_output( + universal: HookUniversalOutputWire, + decision: Option, + reason: Option, + event_name: &str, +) -> StopOutput { + let should_block = matches!(decision, Some(BlockDecisionWire::Block)); let invalid_block_reason = if should_block - && match wire.reason.as_deref() { + && match reason.as_deref() { Some(reason) => reason.trim().is_empty(), None => true, } { - Some(invalid_block_message("Stop")) + Some(invalid_block_message(event_name)) } else { None }; - Some(StopOutput { - universal: UniversalOutput::from(wire.universal), + StopOutput { + universal: UniversalOutput::from(universal), should_block: should_block && invalid_block_reason.is_none(), - reason: wire.reason, + reason, invalid_block_reason, - }) + } } impl From for UniversalOutput { diff --git a/codex-rs/hooks/src/engine/schema_loader.rs b/codex-rs/hooks/src/engine/schema_loader.rs index 2b1994f28d..655e283124 100644 --- a/codex-rs/hooks/src/engine/schema_loader.rs +++ b/codex-rs/hooks/src/engine/schema_loader.rs @@ -18,6 +18,8 @@ pub(crate) struct GeneratedHookSchemas { pub session_start_command_output: Value, pub subagent_start_command_input: Value, pub subagent_start_command_output: Value, + pub subagent_stop_command_input: Value, + pub subagent_stop_command_output: Value, pub user_prompt_submit_command_input: Value, pub user_prompt_submit_command_output: Value, pub stop_command_input: Value, @@ -83,6 +85,14 @@ pub(crate) fn generated_hook_schemas() -> &'static GeneratedHookSchemas { "subagent-start.command.output", include_str!("../../schema/generated/subagent-start.command.output.schema.json"), ), + subagent_stop_command_input: parse_json_schema( + "subagent-stop.command.input", + include_str!("../../schema/generated/subagent-stop.command.input.schema.json"), + ), + subagent_stop_command_output: parse_json_schema( + "subagent-stop.command.output", + include_str!("../../schema/generated/subagent-stop.command.output.schema.json"), + ), user_prompt_submit_command_input: parse_json_schema( "user-prompt-submit.command.input", include_str!("../../schema/generated/user-prompt-submit.command.input.schema.json"), @@ -130,6 +140,8 @@ mod tests { assert_eq!(schemas.session_start_command_output["type"], "object"); assert_eq!(schemas.subagent_start_command_input["type"], "object"); assert_eq!(schemas.subagent_start_command_output["type"], "object"); + assert_eq!(schemas.subagent_stop_command_input["type"], "object"); + assert_eq!(schemas.subagent_stop_command_output["type"], "object"); assert_eq!(schemas.user_prompt_submit_command_input["type"], "object"); assert_eq!(schemas.user_prompt_submit_command_output["type"], "object"); assert_eq!(schemas.stop_command_input["type"], "object"); diff --git a/codex-rs/hooks/src/events/common.rs b/codex-rs/hooks/src/events/common.rs index f96de58020..c97129ebef 100644 --- a/codex-rs/hooks/src/events/common.rs +++ b/codex-rs/hooks/src/events/common.rs @@ -105,6 +105,7 @@ pub(crate) fn matcher_pattern_for_event( | HookEventName::PostToolUse | HookEventName::SessionStart | HookEventName::SubagentStart + | HookEventName::SubagentStop | HookEventName::PreCompact | HookEventName::PostCompact => matcher, HookEventName::UserPromptSubmit | HookEventName::Stop => None, diff --git a/codex-rs/hooks/src/events/stop.rs b/codex-rs/hooks/src/events/stop.rs index 3cd2d44270..24920c569b 100644 --- a/codex-rs/hooks/src/events/stop.rs +++ b/codex-rs/hooks/src/events/stop.rs @@ -18,6 +18,7 @@ use crate::engine::dispatcher; use crate::engine::output_parser; use crate::schema::NullableString; use crate::schema::StopCommandInput; +use crate::schema::SubagentStopCommandInput; #[derive(Debug, Clone)] pub struct StopRequest { @@ -29,9 +30,36 @@ pub struct StopRequest { pub permission_mode: String, pub stop_hook_active: bool, pub last_assistant_message: Option, + pub target: StopHookTarget, } -#[derive(Debug)] +#[derive(Debug, Clone)] +pub enum StopHookTarget { + Stop, + SubagentStop { + agent_id: String, + agent_type: String, + agent_transcript_path: Option, + }, +} + +impl StopHookTarget { + fn event_name(&self) -> HookEventName { + match self { + Self::Stop => HookEventName::Stop, + Self::SubagentStop { .. } => HookEventName::SubagentStop, + } + } + + fn matcher_input(&self) -> Option<&str> { + match self { + Self::Stop => None, + Self::SubagentStop { agent_type, .. } => Some(agent_type.as_str()), + } + } +} + +#[derive(Debug, Default)] pub struct StopOutcome { pub hook_events: Vec, pub should_stop: bool, @@ -52,12 +80,16 @@ struct StopHandlerData { pub(crate) fn preview( handlers: &[ConfiguredHandler], - _request: &StopRequest, + request: &StopRequest, ) -> Vec { - dispatcher::select_handlers(handlers, HookEventName::Stop, /*matcher_input*/ None) - .into_iter() - .map(|handler| dispatcher::running_summary(&handler)) - .collect() + dispatcher::select_handlers( + handlers, + request.target.event_name(), + request.target.matcher_input(), + ) + .into_iter() + .map(|handler| dispatcher::running_summary(&handler)) + .collect() } pub(crate) async fn run( @@ -65,8 +97,11 @@ pub(crate) async fn run( shell: &CommandShell, request: StopRequest, ) -> StopOutcome { - let matched = - dispatcher::select_handlers(handlers, HookEventName::Stop, /*matcher_input*/ None); + let matched = dispatcher::select_handlers( + handlers, + request.target.event_name(), + request.target.matcher_input(), + ); if matched.is_empty() { return StopOutcome { hook_events: Vec::new(), @@ -78,24 +113,67 @@ pub(crate) async fn run( }; } - let input_json = match serde_json::to_string(&StopCommandInput { - session_id: request.session_id.to_string(), - turn_id: request.turn_id.clone(), - transcript_path: NullableString::from_path(request.transcript_path.clone()), - cwd: request.cwd.display().to_string(), - hook_event_name: "Stop".to_string(), - model: request.model.clone(), - permission_mode: request.permission_mode.clone(), - stop_hook_active: request.stop_hook_active, - last_assistant_message: NullableString::from_string(request.last_assistant_message.clone()), - }) { - Ok(input_json) => input_json, - Err(error) => { - return serialization_failure_outcome(common::serialization_failure_hook_events( - matched, - Some(request.turn_id), - format!("failed to serialize stop hook input: {error}"), - )); + let input_json = match request.target { + StopHookTarget::Stop => { + let input = StopCommandInput { + session_id: request.session_id.to_string(), + turn_id: request.turn_id.clone(), + transcript_path: NullableString::from_path(request.transcript_path.clone()), + cwd: request.cwd.display().to_string(), + hook_event_name: "Stop".to_string(), + model: request.model.clone(), + permission_mode: request.permission_mode.clone(), + stop_hook_active: request.stop_hook_active, + last_assistant_message: NullableString::from_string( + request.last_assistant_message.clone(), + ), + }; + match serde_json::to_string(&input) { + Ok(input_json) => input_json, + Err(error) => { + return serialization_failure_outcome( + common::serialization_failure_hook_events( + matched, + Some(request.turn_id), + format!("failed to serialize stop hook input: {error}"), + ), + ); + } + } + } + StopHookTarget::SubagentStop { + agent_id, + agent_type, + agent_transcript_path, + } => { + let input = SubagentStopCommandInput { + session_id: request.session_id.to_string(), + turn_id: request.turn_id.clone(), + transcript_path: NullableString::from_path(request.transcript_path.clone()), + agent_transcript_path: NullableString::from_path(agent_transcript_path), + cwd: request.cwd.display().to_string(), + hook_event_name: "SubagentStop".to_string(), + model: request.model.clone(), + permission_mode: request.permission_mode.clone(), + stop_hook_active: request.stop_hook_active, + agent_id, + agent_type, + last_assistant_message: NullableString::from_string( + request.last_assistant_message.clone(), + ), + }; + match serde_json::to_string(&input) { + Ok(input_json) => input_json, + Err(error) => { + return serialization_failure_outcome( + common::serialization_failure_hook_events( + matched, + Some(request.turn_id), + format!("failed to serialize subagent stop hook input: {error}"), + ), + ); + } + } } }; @@ -133,6 +211,12 @@ fn parse_completed( let mut should_block = false; let mut block_reason = None; let mut continuation_prompt = None; + let hook_event_name = match handler.event_name { + HookEventName::Stop | HookEventName::SubagentStop => handler.event_name, + event_name => { + panic!("expected stop hook event, got {event_name:?}"); + } + }; match run_result.error.as_deref() { Some(error) => { @@ -146,7 +230,13 @@ fn parse_completed( Some(0) => { let trimmed_stdout = run_result.stdout.trim(); if trimmed_stdout.is_empty() { - } else if let Some(parsed) = output_parser::parse_stop(&run_result.stdout) { + } else if let Some(parsed) = match hook_event_name { + HookEventName::Stop => output_parser::parse_stop(&run_result.stdout), + HookEventName::SubagentStop => { + output_parser::parse_subagent_stop(&run_result.stdout) + } + _ => unreachable!("validated stop hook event"), + } { if let Some(system_message) = parsed.universal.system_message { entries.push(HookOutputEntry { kind: HookOutputEntryKind::Warning, @@ -186,9 +276,12 @@ fn parse_completed( status = HookRunStatus::Failed; entries.push(HookOutputEntry { kind: HookOutputEntryKind::Error, - text: - "Stop hook returned decision:block without a non-empty reason" - .to_string(), + text: match hook_event_name { + HookEventName::Stop => "Stop hook returned decision:block without a non-empty reason", + HookEventName::SubagentStop => "SubagentStop hook returned decision:block without a non-empty reason", + _ => unreachable!("validated stop hook event"), + } + .to_string(), }); } } @@ -196,7 +289,14 @@ fn parse_completed( status = HookRunStatus::Failed; entries.push(HookOutputEntry { kind: HookOutputEntryKind::Error, - text: "hook returned invalid stop hook JSON output".to_string(), + text: match hook_event_name { + HookEventName::Stop => "hook returned invalid stop hook JSON output", + HookEventName::SubagentStop => { + "hook returned invalid subagent stop hook JSON output" + } + _ => unreachable!("validated stop hook event"), + } + .to_string(), }); } } @@ -214,9 +314,16 @@ fn parse_completed( status = HookRunStatus::Failed; entries.push(HookOutputEntry { kind: HookOutputEntryKind::Error, - text: - "Stop hook exited with code 2 but did not write a continuation prompt to stderr" - .to_string(), + text: match hook_event_name { + HookEventName::Stop => { + "Stop hook exited with code 2 but did not write a continuation prompt to stderr" + } + HookEventName::SubagentStop => { + "SubagentStop hook exited with code 2 but did not write a continuation prompt to stderr" + } + _ => unreachable!("validated stop hook event"), + } + .to_string(), }); } } diff --git a/codex-rs/hooks/src/lib.rs b/codex-rs/hooks/src/lib.rs index 5675d11e71..70ee3b4540 100644 --- a/codex-rs/hooks/src/lib.rs +++ b/codex-rs/hooks/src/lib.rs @@ -15,7 +15,7 @@ pub use declarations::PluginHookDeclaration; pub use declarations::plugin_hook_declarations; pub use engine::HookListEntry; /// Hook event names as they appear in hooks JSON and config files. -pub const HOOK_EVENT_NAMES: [&str; 9] = [ +pub const HOOK_EVENT_NAMES: [&str; 10] = [ "PreToolUse", "PermissionRequest", "PostToolUse", @@ -24,6 +24,7 @@ pub const HOOK_EVENT_NAMES: [&str; 9] = [ "SessionStart", "UserPromptSubmit", "SubagentStart", + "SubagentStop", "Stop", ]; @@ -32,7 +33,7 @@ pub const HOOK_EVENT_NAMES: [&str; 9] = [ /// Other events can appear in hooks JSON, but Codex ignores their matcher /// fields because those events do not dispatch against a tool, compaction /// trigger, or session-start source. -pub const HOOK_EVENT_NAMES_WITH_MATCHERS: [&str; 7] = [ +pub const HOOK_EVENT_NAMES_WITH_MATCHERS: [&str; 8] = [ "PreToolUse", "PermissionRequest", "PostToolUse", @@ -40,6 +41,7 @@ pub const HOOK_EVENT_NAMES_WITH_MATCHERS: [&str; 7] = [ "PostCompact", "SessionStart", "SubagentStart", + "SubagentStop", ]; pub use events::compact::PostCompactRequest; @@ -57,6 +59,7 @@ pub use events::session_start::SessionStartOutcome; pub use events::session_start::SessionStartRequest; pub use events::session_start::SessionStartSource; pub use events::session_start::StartHookTarget; +pub use events::stop::StopHookTarget; pub use events::stop::StopOutcome; pub use events::stop::StopRequest; pub use events::user_prompt_submit::UserPromptSubmitOutcome; @@ -87,6 +90,7 @@ pub fn hook_event_key_label(event_name: HookEventName) -> &'static str { HookEventName::SessionStart => "session_start", HookEventName::UserPromptSubmit => "user_prompt_submit", HookEventName::SubagentStart => "subagent_start", + HookEventName::SubagentStop => "subagent_stop", HookEventName::Stop => "stop", } } diff --git a/codex-rs/hooks/src/schema.rs b/codex-rs/hooks/src/schema.rs index 15a655c976..bbed57d36d 100644 --- a/codex-rs/hooks/src/schema.rs +++ b/codex-rs/hooks/src/schema.rs @@ -29,6 +29,8 @@ const USER_PROMPT_SUBMIT_INPUT_FIXTURE: &str = "user-prompt-submit.command.input const USER_PROMPT_SUBMIT_OUTPUT_FIXTURE: &str = "user-prompt-submit.command.output.schema.json"; const SUBAGENT_START_INPUT_FIXTURE: &str = "subagent-start.command.input.schema.json"; const SUBAGENT_START_OUTPUT_FIXTURE: &str = "subagent-start.command.output.schema.json"; +const SUBAGENT_STOP_INPUT_FIXTURE: &str = "subagent-stop.command.input.schema.json"; +const SUBAGENT_STOP_OUTPUT_FIXTURE: &str = "subagent-stop.command.output.schema.json"; const STOP_INPUT_FIXTURE: &str = "stop.command.input.schema.json"; const STOP_OUTPUT_FIXTURE: &str = "stop.command.output.schema.json"; @@ -91,6 +93,8 @@ pub(crate) enum HookEventNameWire { UserPromptSubmit, #[serde(rename = "SubagentStart")] SubagentStart, + #[serde(rename = "SubagentStop")] + SubagentStop, #[serde(rename = "Stop")] Stop, } @@ -399,6 +403,21 @@ pub(crate) struct StopCommandOutputWire { pub reason: Option, } +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "camelCase")] +#[serde(deny_unknown_fields)] +#[schemars(rename = "subagent-stop.command.output")] +pub(crate) struct SubagentStopCommandOutputWire { + #[serde(flatten)] + pub universal: HookUniversalOutputWire, + #[serde(default)] + pub decision: Option, + /// Claude requires `reason` when `decision` is `block`; we enforce that + /// semantic rule during output parsing rather than in the JSON schema. + #[serde(default)] + pub reason: Option, +} + #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)] pub(crate) enum BlockDecisionWire { #[serde(rename = "block")] @@ -495,6 +514,27 @@ pub(crate) struct StopCommandInput { pub last_assistant_message: NullableString, } +#[derive(Debug, Clone, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +#[schemars(rename = "subagent-stop.command.input")] +pub(crate) struct SubagentStopCommandInput { + pub session_id: String, + /// Codex extension: expose the active turn id to internal turn-scoped hooks. + pub turn_id: String, + pub transcript_path: NullableString, + pub agent_transcript_path: NullableString, + pub cwd: String, + #[schemars(schema_with = "subagent_stop_hook_event_name_schema")] + pub hook_event_name: String, + pub model: String, + #[schemars(schema_with = "permission_mode_schema")] + pub permission_mode: String, + pub stop_hook_active: bool, + pub agent_id: String, + pub agent_type: String, + pub last_assistant_message: NullableString, +} + pub fn write_schema_fixtures(schema_root: &Path) -> anyhow::Result<()> { let generated_dir = schema_root.join(GENERATED_DIR); ensure_empty_dir(&generated_dir)?; @@ -563,6 +603,14 @@ pub fn write_schema_fixtures(schema_root: &Path) -> anyhow::Result<()> { &generated_dir.join(SUBAGENT_START_OUTPUT_FIXTURE), schema_json::()?, )?; + write_schema( + &generated_dir.join(SUBAGENT_STOP_INPUT_FIXTURE), + schema_json::()?, + )?; + write_schema( + &generated_dir.join(SUBAGENT_STOP_OUTPUT_FIXTURE), + schema_json::()?, + )?; write_schema( &generated_dir.join(STOP_INPUT_FIXTURE), schema_json::()?, @@ -658,6 +706,10 @@ fn subagent_start_hook_event_name_schema(_gen: &mut SchemaGenerator) -> Schema { string_const_schema("SubagentStart") } +fn subagent_stop_hook_event_name_schema(_gen: &mut SchemaGenerator) -> Schema { + string_const_schema("SubagentStop") +} + fn stop_hook_event_name_schema(_gen: &mut SchemaGenerator) -> Schema { string_const_schema("Stop") } @@ -730,8 +782,11 @@ mod tests { use super::STOP_OUTPUT_FIXTURE; use super::SUBAGENT_START_INPUT_FIXTURE; use super::SUBAGENT_START_OUTPUT_FIXTURE; + use super::SUBAGENT_STOP_INPUT_FIXTURE; + use super::SUBAGENT_STOP_OUTPUT_FIXTURE; use super::StopCommandInput; use super::SubagentStartCommandInput; + use super::SubagentStopCommandInput; use super::USER_PROMPT_SUBMIT_INPUT_FIXTURE; use super::USER_PROMPT_SUBMIT_OUTPUT_FIXTURE; use super::UserPromptSubmitCommandInput; @@ -791,6 +846,12 @@ mod tests { SUBAGENT_START_OUTPUT_FIXTURE => { include_str!("../schema/generated/subagent-start.command.output.schema.json") } + SUBAGENT_STOP_INPUT_FIXTURE => { + include_str!("../schema/generated/subagent-stop.command.input.schema.json") + } + SUBAGENT_STOP_OUTPUT_FIXTURE => { + include_str!("../schema/generated/subagent-stop.command.output.schema.json") + } STOP_INPUT_FIXTURE => { include_str!("../schema/generated/stop.command.input.schema.json") } @@ -828,6 +889,8 @@ mod tests { USER_PROMPT_SUBMIT_OUTPUT_FIXTURE, SUBAGENT_START_INPUT_FIXTURE, SUBAGENT_START_OUTPUT_FIXTURE, + SUBAGENT_STOP_INPUT_FIXTURE, + SUBAGENT_STOP_OUTPUT_FIXTURE, STOP_INPUT_FIXTURE, STOP_OUTPUT_FIXTURE, ] { @@ -875,6 +938,11 @@ mod tests { .expect("serialize subagent start input schema"), ) .expect("parse subagent start input schema"); + let subagent_stop: Value = serde_json::from_slice( + &schema_json::() + .expect("serialize subagent stop input schema"), + ) + .expect("parse subagent stop input schema"); let stop: Value = serde_json::from_slice( &schema_json::().expect("serialize stop input schema"), ) @@ -888,6 +956,7 @@ mod tests { &post_compact, &user_prompt_submit, &subagent_start, + &subagent_stop, &stop, ] { assert_eq!(schema["properties"]["turn_id"]["type"], "string"); diff --git a/codex-rs/model-provider/src/amazon_bedrock/catalog.rs b/codex-rs/model-provider/src/amazon_bedrock/catalog.rs index d6fe1de095..8fec7f835e 100644 --- a/codex-rs/model-provider/src/amazon_bedrock/catalog.rs +++ b/codex-rs/model-provider/src/amazon_bedrock/catalog.rs @@ -55,6 +55,7 @@ fn gpt_5_4_cmb_bedrock_model(priority: i32) -> ModelInfo { name: SPEED_TIER_FAST.to_string(), description: "Fastest inference with increased plan usage".to_string(), }], + default_service_tier: None, availability_nux: None, upgrade: None, base_instructions: BASE_INSTRUCTIONS.to_string(), @@ -96,6 +97,7 @@ fn bedrock_oss_model(slug: &str, display_name: &str, priority: i32) -> ModelInfo priority, additional_speed_tiers: Vec::new(), service_tiers: Vec::new(), + default_service_tier: None, availability_nux: None, upgrade: None, base_instructions: BASE_INSTRUCTIONS.to_string(), diff --git a/codex-rs/models-manager/src/model_info.rs b/codex-rs/models-manager/src/model_info.rs index 774dd3eaca..17b843440a 100644 --- a/codex-rs/models-manager/src/model_info.rs +++ b/codex-rs/models-manager/src/model_info.rs @@ -77,6 +77,7 @@ pub fn model_info_from_slug(slug: &str) -> ModelInfo { priority: 99, additional_speed_tiers: Vec::new(), service_tiers: Vec::new(), + default_service_tier: None, availability_nux: None, upgrade: None, base_instructions: BASE_INSTRUCTIONS.to_string(), diff --git a/codex-rs/network-proxy/README.md b/codex-rs/network-proxy/README.md index d9eecf4f6a..8c2117b4dc 100644 --- a/codex-rs/network-proxy/README.md +++ b/codex-rs/network-proxy/README.md @@ -33,8 +33,7 @@ allow_upstream_proxy = true # If you want to expose these listeners beyond localhost, you must opt in explicitly. dangerously_allow_non_loopback_proxy = false mode = "full" # default when unset; use "limited" for read-only mode -# When true, HTTPS CONNECT can be terminated so limited-mode method policy still applies. -mitm = false +# HTTPS MITM is enabled automatically when `mode = "limited"` or when MITM hooks are configured. # CA cert/key are managed internally under $CODEX_HOME/proxy/ (ca.pem + ca.key). # If false, local/private networking is rejected. Explicit allowlisting of local IP literals @@ -57,6 +56,17 @@ dangerously_allow_all_unix_sockets = false "::1" = "allow" "evil.example" = "deny" +# MITM hooks match HTTPS requests after CONNECT is terminated. +[permissions.workspace.network.mitm.hooks.github_write] +host = "api.github.com" +methods = ["POST", "PUT"] +path_prefixes = ["/repos/openai/"] +action = ["strip_auth"] + +# Named actions can be shared across hooks and overridden by higher-precedence config layers. +[permissions.workspace.network.mitm.actions.strip_auth] +strip_request_headers = ["authorization"] + # macOS-only: allows proxying to a unix socket when request includes `x-unix-socket: /path`. [permissions.workspace.network.unix_sockets] "/tmp/example.sock" = "allow" diff --git a/codex-rs/network-proxy/src/mitm.rs b/codex-rs/network-proxy/src/mitm.rs index fdcb9d0aa2..9ee5bfc253 100644 --- a/codex-rs/network-proxy/src/mitm.rs +++ b/codex-rs/network-proxy/src/mitm.rs @@ -16,6 +16,7 @@ use crate::upstream::UpstreamClient; use anyhow::Context as _; use anyhow::Result; use anyhow::anyhow; +use codex_utils_rustls_provider::ensure_rustls_crypto_provider; use rama_core::Layer; use rama_core::Service; use rama_core::bytes::Bytes; @@ -97,6 +98,8 @@ impl std::fmt::Debug for MitmState { impl MitmState { pub(crate) fn new(config: MitmUpstreamConfig) -> Result { + ensure_rustls_crypto_provider(); + // MITM exists when HTTPS policy depends on the inner request: limited-mode method clamps // and host-specific hooks both need visibility after CONNECT is established. We // generate/load a local CA and issue per-host leaf certs so we can terminate TLS and diff --git a/codex-rs/network-proxy/src/mitm_tests.rs b/codex-rs/network-proxy/src/mitm_tests.rs index 098eb745b1..0823be517c 100644 --- a/codex-rs/network-proxy/src/mitm_tests.rs +++ b/codex-rs/network-proxy/src/mitm_tests.rs @@ -186,7 +186,7 @@ async fn mitm_policy_allows_matching_hooked_write_in_full_mode() { assert!( response.is_none(), - "matching hook should be allowed in full mode" + "matching hook should bypass method clamp" ); assert_eq!(app_state.blocked_snapshot().await.unwrap().len(), 0); } diff --git a/codex-rs/protocol/src/config_types.rs b/codex-rs/protocol/src/config_types.rs index b4b4759c9b..550dbdaf3a 100644 --- a/codex-rs/protocol/src/config_types.rs +++ b/codex-rs/protocol/src/config_types.rs @@ -432,6 +432,12 @@ pub enum ServiceTier { Flex, } +/// Request/config sentinel for explicit standard routing. +/// +/// This is not a catalog service tier id. It means the user intentionally +/// selected no service tier, so model catalog defaults should not apply. +pub const SERVICE_TIER_DEFAULT_REQUEST_VALUE: &str = "default"; + impl ServiceTier { pub const fn request_value(self) -> &'static str { match self { diff --git a/codex-rs/protocol/src/items.rs b/codex-rs/protocol/src/items.rs index 9263d54796..7d12579564 100644 --- a/codex-rs/protocol/src/items.rs +++ b/codex-rs/protocol/src/items.rs @@ -179,6 +179,9 @@ pub struct McpToolCallItem { #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub mcp_app_resource_uri: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub plugin_id: Option, pub status: McpToolCallStatus, #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] @@ -530,6 +533,7 @@ impl McpToolCallItem { arguments: (!self.arguments.is_null()).then(|| self.arguments.clone()), }, mcp_app_resource_uri: self.mcp_app_resource_uri.clone(), + plugin_id: self.plugin_id.clone(), }) } @@ -548,6 +552,7 @@ impl McpToolCallItem { arguments: (!self.arguments.is_null()).then(|| self.arguments.clone()), }, mcp_app_resource_uri: self.mcp_app_resource_uri.clone(), + plugin_id: self.plugin_id.clone(), duration: self.duration?, result, })) diff --git a/codex-rs/protocol/src/openai_models.rs b/codex-rs/protocol/src/openai_models.rs index d51e70ddf1..d0a58b5024 100644 --- a/codex-rs/protocol/src/openai_models.rs +++ b/codex-rs/protocol/src/openai_models.rs @@ -17,6 +17,7 @@ use ts_rs::TS; use crate::config_types::Personality; use crate::config_types::ReasoningSummary; +use crate::config_types::SERVICE_TIER_DEFAULT_REQUEST_VALUE; use crate::config_types::ServiceTier; use crate::config_types::Verbosity; @@ -147,6 +148,9 @@ pub struct ModelPreset { /// Service tiers this model can run with. #[serde(default)] pub service_tiers: Vec, + /// Catalog default service tier id for this model. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub default_service_tier: Option, /// Whether this is the default model for new users. pub is_default: bool, /// recommended upgrade model @@ -270,6 +274,8 @@ pub struct ModelInfo { pub additional_speed_tiers: Vec, #[serde(default)] pub service_tiers: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub default_service_tier: Option, pub availability_nux: Option, pub upgrade: Option, pub base_instructions: String, @@ -455,6 +461,7 @@ impl From for ModelPreset { supports_personality, additional_speed_tiers: info.additional_speed_tiers, service_tiers: info.service_tiers, + default_service_tier: info.default_service_tier, is_default: false, // default is the highest priority available model upgrade: info.upgrade.as_ref().map(|upgrade| ModelUpgrade { id: upgrade.model.clone(), @@ -493,6 +500,13 @@ impl ModelInfo { .iter() .any(|tier| tier.id == service_tier) } + + pub fn service_tier_for_request(&self, service_tier: Option) -> Option { + service_tier.filter(|service_tier| { + service_tier != SERVICE_TIER_DEFAULT_REQUEST_VALUE + && self.supports_service_tier(service_tier) + }) + } } impl ModelPreset { @@ -576,6 +590,7 @@ mod tests { priority: 1, additional_speed_tiers: Vec::new(), service_tiers: Vec::new(), + default_service_tier: None, availability_nux: None, upgrade: None, base_instructions: "base".to_string(), @@ -846,6 +861,7 @@ mod tests { message: "Try Spark.".to_string(), }), additional_speed_tiers: vec![SPEED_TIER_FAST.to_string()], + default_service_tier: Some(ServiceTier::Fast.request_value().to_string()), service_tiers: Vec::new(), ..test_model(/*spec*/ None) }); @@ -857,6 +873,10 @@ mod tests { }) ); assert!(preset.supports_fast_mode()); + assert_eq!( + preset.default_service_tier, + Some(ServiceTier::Fast.request_value().to_string()) + ); } #[test] @@ -872,4 +892,60 @@ mod tests { assert!(preset.supports_fast_mode()); } + + #[test] + fn service_tier_for_request_omits_explicit_default_tier() { + let model = ModelInfo { + default_service_tier: Some(ServiceTier::Fast.request_value().to_string()), + service_tiers: vec![ModelServiceTier { + id: ServiceTier::Fast.request_value().to_string(), + name: "Fast".to_string(), + description: "Priority processing.".to_string(), + }], + ..test_model(/*spec*/ None) + }; + + assert_eq!( + model.service_tier_for_request(Some(SERVICE_TIER_DEFAULT_REQUEST_VALUE.to_string())), + None + ); + } + + #[test] + fn service_tier_for_request_filters_unsupported_tiers() { + let model = ModelInfo { + default_service_tier: Some(ServiceTier::Fast.request_value().to_string()), + service_tiers: vec![ModelServiceTier { + id: ServiceTier::Fast.request_value().to_string(), + name: "Fast".to_string(), + description: "Priority processing.".to_string(), + }], + ..test_model(/*spec*/ None) + }; + + assert_eq!( + model.service_tier_for_request(Some(ServiceTier::Fast.request_value().to_string())), + Some(ServiceTier::Fast.request_value().to_string()) + ); + assert_eq!( + model.service_tier_for_request(Some("unsupported".to_string())), + None + ); + assert_eq!(model.service_tier_for_request(/*service_tier*/ None), None); + } + + #[test] + fn service_tier_for_request_does_not_apply_catalog_default() { + let model = ModelInfo { + default_service_tier: Some(ServiceTier::Fast.request_value().to_string()), + service_tiers: vec![ModelServiceTier { + id: ServiceTier::Fast.request_value().to_string(), + name: "Fast".to_string(), + description: "Priority processing.".to_string(), + }], + ..test_model(/*spec*/ None) + }; + + assert_eq!(model.service_tier_for_request(/*service_tier*/ None), None); + } } diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 2647d3a878..b0f34bae4d 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -1338,6 +1338,7 @@ pub enum HookEventName { SessionStart, UserPromptSubmit, SubagentStart, + SubagentStop, Stop, } @@ -2185,6 +2186,9 @@ pub struct McpToolCallBeginEvent { #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub mcp_app_resource_uri: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub plugin_id: Option, } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS, PartialEq)] @@ -2195,6 +2199,9 @@ pub struct McpToolCallEndEvent { #[serde(default, skip_serializing_if = "Option::is_none")] #[ts(optional)] pub mcp_app_resource_uri: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub plugin_id: Option, #[ts(type = "string")] pub duration: Duration, /// Result of the tool call. Note this could be an error. @@ -4535,6 +4542,7 @@ mod tests { tool: "tool".into(), arguments: json!({"arg": "value"}), mcp_app_resource_uri: Some("app://connector".into()), + plugin_id: Some("sample@test".into()), status: McpToolCallStatus::InProgress, result: None, error: None, @@ -4553,6 +4561,7 @@ mod tests { event.mcp_app_resource_uri.as_deref(), Some("app://connector") ); + assert_eq!(event.plugin_id.as_deref(), Some("sample@test")); } _ => panic!("expected McpToolCallBegin event"), } @@ -4640,6 +4649,7 @@ mod tests { tool: "tool".into(), arguments: json!({"arg": "value"}), mcp_app_resource_uri: Some("app://connector".into()), + plugin_id: Some("sample@test".into()), status: McpToolCallStatus::Completed, result: Some(CallToolResult { content: vec![json!({"type": "text", "text": "ok"})], @@ -4663,6 +4673,7 @@ mod tests { event.mcp_app_resource_uri.as_deref(), Some("app://connector") ); + assert_eq!(event.plugin_id.as_deref(), Some("sample@test")); assert_eq!(event.duration, Duration::from_millis(42)); assert!(event.is_success()); } diff --git a/codex-rs/tools/src/tool_config_tests.rs b/codex-rs/tools/src/tool_config_tests.rs index 8ce68acbba..033bf07b10 100644 --- a/codex-rs/tools/src/tool_config_tests.rs +++ b/codex-rs/tools/src/tool_config_tests.rs @@ -22,6 +22,7 @@ fn model_with_shell_type(shell_type: ConfigShellToolType) -> ModelInfo { priority: 0, additional_speed_tiers: Vec::new(), service_tiers: Vec::new(), + default_service_tier: None, availability_nux: None, upgrade: None, base_instructions: String::new(), diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index ce0eb0ff93..e3399ea5e5 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -767,6 +767,8 @@ impl App { self.chat_widget.set_model(&model); self.sync_active_thread_model_setting(app_server, model) .await; + self.sync_active_thread_service_tier_to_cached_session() + .await; } AppEvent::UpdatePersonality(personality) => { self.on_update_personality(personality); @@ -1325,9 +1327,6 @@ impl App { profile, service_tier.as_deref(), ); - if service_tier.is_none() { - self.config.notices.fast_default_opt_out = Some(true); - } match crate::config_update::write_config_batch(app_server.request_handle(), edits) .await { diff --git a/codex-rs/tui/src/app/session_lifecycle.rs b/codex-rs/tui/src/app/session_lifecycle.rs index 6c87894434..bf5ffdad36 100644 --- a/codex-rs/tui/src/app/session_lifecycle.rs +++ b/codex-rs/tui/src/app/session_lifecycle.rs @@ -656,7 +656,6 @@ impl App { pub(super) fn fresh_session_config(&self) -> Config { let mut config = self.config.clone(); config.service_tier = self.chat_widget.configured_service_tier(); - config.notices.fast_default_opt_out = self.chat_widget.fast_default_opt_out(); config } pub(super) async fn resume_target_session( diff --git a/codex-rs/tui/src/app/side.rs b/codex-rs/tui/src/app/side.rs index 492639f139..04831e16e4 100644 --- a/codex-rs/tui/src/app/side.rs +++ b/codex-rs/tui/src/app/side.rs @@ -464,7 +464,6 @@ impl App { } fork_config.model_reasoning_effort = self.chat_widget.current_reasoning_effort(); fork_config.service_tier = self.chat_widget.configured_service_tier(); - fork_config.notices.fast_default_opt_out = self.chat_widget.fast_default_opt_out(); fork_config.ephemeral = true; fork_config.developer_instructions = Some(Self::side_developer_instructions( fork_config.developer_instructions.as_deref(), diff --git a/codex-rs/tui/src/app_server_session.rs b/codex-rs/tui/src/app_server_session.rs index 9eca24e051..4597c60913 100644 --- a/codex-rs/tui/src/app_server_session.rs +++ b/codex-rs/tui/src/app_server_session.rs @@ -6,6 +6,7 @@ use crate::bottom_pane::FeedbackAudience; use crate::legacy_core::config::Config; use crate::permission_compat::legacy_compatible_permission_profile; +use crate::service_tier_resolution; use crate::session_state::MessageHistoryMetadata; use crate::session_state::ThreadSessionState; use crate::status::StatusAccountDisplay; @@ -107,6 +108,7 @@ use codex_app_server_protocol::UserInput; use codex_otel::TelemetryAuthMode; use codex_protocol::ThreadId; use codex_protocol::approvals::GuardianAssessmentEvent; +use codex_protocol::config_types::SERVICE_TIER_DEFAULT_REQUEST_VALUE; use codex_protocol::models::ActivePermissionProfile; use codex_protocol::models::PermissionProfile; use codex_protocol::models::ResponseItem; @@ -164,6 +166,8 @@ pub(crate) struct AppServerSession { remote_cwd_override: Option, thread_params_mode: ThreadParamsMode, thread_settings_update_supported: bool, + default_model: Option, + available_models: Vec, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -205,6 +209,8 @@ impl AppServerSession { remote_cwd_override: None, thread_params_mode, thread_settings_update_supported: true, + default_model: None, + available_models: Vec::new(), } } @@ -254,6 +260,8 @@ impl AppServerSession { }) .or_else(|| available_models.first().map(|model| model.model.clone())) .wrap_err("model/list returned no models for TUI bootstrap")?; + self.default_model = Some(default_model.clone()); + self.available_models = available_models.clone(); let ( account_email, @@ -365,12 +373,13 @@ impl AppServerSession { session_start_source: Option, ) -> Result { let request_id = self.next_request_id(); + let session_config = self.session_config_with_effective_service_tier(config); let response: ThreadStartResponse = self .client .request_typed(ClientRequest::ThreadStart { request_id, params: thread_start_params_from_config( - config, + &session_config, self.thread_params_mode(), self.remote_cwd_override.as_deref(), session_start_source, @@ -389,12 +398,13 @@ impl AppServerSession { thread_id: ThreadId, ) -> Result { let request_id = self.next_request_id(); + let session_config = self.session_config_with_effective_service_tier(&config); let response: ThreadResumeResponse = self .client .request_typed(ClientRequest::ThreadResume { request_id, params: thread_resume_params_from_config( - config.clone(), + session_config, thread_id, self.thread_params_mode(), self.remote_cwd_override.as_deref(), @@ -420,12 +430,13 @@ impl AppServerSession { thread_id: ThreadId, ) -> Result { let request_id = self.next_request_id(); + let session_config = self.session_config_with_effective_service_tier(&config); let response: ThreadForkResponse = self .client .request_typed(ClientRequest::ThreadFork { request_id, params: thread_fork_params_from_config( - config.clone(), + session_config, thread_id, self.thread_params_mode(), self.remote_cwd_override.as_deref(), @@ -448,6 +459,32 @@ impl AppServerSession { self.thread_params_mode } + fn session_config_with_effective_service_tier(&self, config: &Config) -> Config { + let Some(model) = config.model.as_deref().or(self.default_model.as_deref()) else { + return config.clone(); + }; + let mut session_config = config.clone(); + match service_tier_resolution::service_tier_update_for_core( + config, + model, + &self.available_models, + ) { + Some(Some(service_tier)) => { + session_config.service_tier = Some(service_tier); + session_config.notices.fast_default_opt_out = None; + } + Some(None) => { + session_config.service_tier = Some(SERVICE_TIER_DEFAULT_REQUEST_VALUE.to_string()); + session_config.notices.fast_default_opt_out = None; + } + None => { + session_config.service_tier = None; + session_config.notices.fast_default_opt_out = None; + } + } + session_config + } + async fn fork_parent_title_from_app_server( &mut self, forked_from_id: Option<&str>, @@ -1159,6 +1196,7 @@ fn model_preset_from_api_model(model: ApiModel) -> ModelPreset { description: service_tier.description, }) .collect(), + default_service_tier: model.default_service_tier, is_default: model.is_default, upgrade, show_in_picker: !model.hidden, @@ -1219,11 +1257,10 @@ fn config_request_overrides_from_config( } fn service_tier_override_from_config(config: &Config) -> Option> { - config - .service_tier - .clone() - .map(Some) - .or_else(|| (config.notices.fast_default_opt_out == Some(true)).then_some(None)) + config.service_tier.clone().map(Some).or_else(|| { + (config.notices.fast_default_opt_out == Some(true)) + .then(|| Some(SERVICE_TIER_DEFAULT_REQUEST_VALUE.to_string())) + }) } fn sandbox_mode_from_permission_profile( diff --git a/codex-rs/tui/src/bottom_pane/hooks_browser_view.rs b/codex-rs/tui/src/bottom_pane/hooks_browser_view.rs index 1202265aa2..ce31abf404 100644 --- a/codex-rs/tui/src/bottom_pane/hooks_browser_view.rs +++ b/codex-rs/tui/src/bottom_pane/hooks_browser_view.rs @@ -737,6 +737,7 @@ fn event_label(event_name: HookEventName) -> &'static str { HookEventName::SessionStart => "SessionStart", HookEventName::UserPromptSubmit => "UserPromptSubmit", HookEventName::SubagentStart => "SubagentStart", + HookEventName::SubagentStop => "SubagentStop", HookEventName::Stop => "Stop", } } @@ -751,6 +752,7 @@ fn event_description(event_name: HookEventName) -> &'static str { HookEventName::SessionStart => "When a new session starts", HookEventName::UserPromptSubmit => "When the user submits a prompt", HookEventName::SubagentStart => "When a subagent is created", + HookEventName::SubagentStop => "Right before a subagent ends its turn", HookEventName::Stop => "Right before Codex ends its turn", } } diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__hooks_browser_view__tests__hooks_browser_events.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__hooks_browser_view__tests__hooks_browser_events.snap index 836a65c3f1..eaf06f6c45 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__hooks_browser_view__tests__hooks_browser_events.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__hooks_browser_view__tests__hooks_browser_events.snap @@ -15,6 +15,7 @@ expression: "render_lines(&view, 112)" SessionStart 0 0 When a new session starts UserPromptSubmit 0 0 When the user submits a prompt SubagentStart 0 0 When a subagent is created + SubagentStop 0 0 Right before a subagent ends its turn Stop 0 0 Right before Codex ends its turn Press enter to view hooks; esc to close diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__hooks_browser_view__tests__hooks_browser_events_with_issues.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__hooks_browser_view__tests__hooks_browser_events_with_issues.snap index fabd9c1707..7dc71463dc 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__hooks_browser_view__tests__hooks_browser_events_with_issues.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__hooks_browser_view__tests__hooks_browser_events_with_issues.snap @@ -19,6 +19,7 @@ expression: "render_lines(&view, 112)" SessionStart 0 0 When a new session starts UserPromptSubmit 0 0 When the user submits a prompt SubagentStart 0 0 When a subagent is created + SubagentStop 0 0 Right before a subagent ends its turn Stop 0 0 Right before Codex ends its turn Press enter to view hooks; esc to close diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__hooks_browser_view__tests__hooks_browser_events_with_review_column.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__hooks_browser_view__tests__hooks_browser_events_with_review_column.snap index dd4e5e33b5..c18657d8a1 100644 --- a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__hooks_browser_view__tests__hooks_browser_events_with_review_column.snap +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__hooks_browser_view__tests__hooks_browser_events_with_review_column.snap @@ -17,6 +17,7 @@ expression: "render_lines(&view, 112)" SessionStart 0 0 0 When a new session starts UserPromptSubmit 0 0 0 When the user submits a prompt SubagentStart 0 0 0 When a subagent is created + SubagentStop 0 0 0 Right before a subagent ends its turn Stop 0 0 0 Right before Codex ends its turn Press t to trust all; enter to review hooks; esc to close diff --git a/codex-rs/tui/src/chatwidget/constructor.rs b/codex-rs/tui/src/chatwidget/constructor.rs index 56bdc6bf68..ef90c85d4c 100644 --- a/codex-rs/tui/src/chatwidget/constructor.rs +++ b/codex-rs/tui/src/chatwidget/constructor.rs @@ -64,7 +64,11 @@ impl ChatWidget { let active_cell = Some(Self::placeholder_session_header_cell(&config)); let current_cwd = Some(config.cwd.to_path_buf()); - let effective_service_tier = config.service_tier.clone(); + let effective_service_tier = crate::service_tier_resolution::effective_service_tier( + &config, + &header_model, + &model_catalog.try_list_models().unwrap_or_default(), + ); let current_terminal_info = terminal_info(); let runtime_keymap = RuntimeKeymap::from_config(&config.tui_keymap).ok(); let default_keymap = RuntimeKeymap::defaults(); diff --git a/codex-rs/tui/src/chatwidget/input_submission.rs b/codex-rs/tui/src/chatwidget/input_submission.rs index 2fd376f139..2c960ee3d5 100644 --- a/codex-rs/tui/src/chatwidget/input_submission.rs +++ b/codex-rs/tui/src/chatwidget/input_submission.rs @@ -331,11 +331,7 @@ impl ChatWidget { .personality .filter(|_| self.config.features.enabled(Feature::Personality)) .filter(|_| self.current_model_supports_personality()); - let service_tier = match self.config.service_tier.clone() { - Some(service_tier) => Some(Some(service_tier)), - None if self.config.notices.fast_default_opt_out == Some(true) => Some(None), - None => None, - }; + let service_tier = self.service_tier_update_for_core(); let active_permission_profile = self.config.permissions.active_permission_profile(); let op = AppCommand::user_turn( items, diff --git a/codex-rs/tui/src/chatwidget/service_tiers.rs b/codex-rs/tui/src/chatwidget/service_tiers.rs index a60af0a69e..bc0a700996 100644 --- a/codex-rs/tui/src/chatwidget/service_tiers.rs +++ b/codex-rs/tui/src/chatwidget/service_tiers.rs @@ -4,14 +4,16 @@ use super::ChatWidget; use crate::app_command::AppCommand; use crate::app_event::AppEvent; use crate::bottom_pane::slash_commands::ServiceTierCommand; +use crate::service_tier_resolution; use codex_features::Feature; +use codex_protocol::config_types::SERVICE_TIER_DEFAULT_REQUEST_VALUE; use codex_protocol::config_types::ServiceTier; use codex_protocol::openai_models::SPEED_TIER_FAST; impl ChatWidget { pub(crate) fn set_service_tier(&mut self, service_tier: Option) { - self.config.service_tier = service_tier.clone(); - self.effective_service_tier = service_tier; + self.config.service_tier = service_tier; + self.refresh_effective_service_tier(); self.refresh_model_dependent_surfaces(); } @@ -23,8 +25,12 @@ impl ChatWidget { self.config.service_tier.clone() } - pub(crate) fn fast_default_opt_out(&self) -> Option { - self.config.notices.fast_default_opt_out + pub(crate) fn service_tier_update_for_core(&self) -> Option> { + service_tier_resolution::service_tier_update_for_core( + &self.config, + self.current_model(), + &self.model_catalog.try_list_models().unwrap_or_default(), + ) } pub(crate) fn should_show_fast_status(&self, model: &str, service_tier: Option<&str>) -> bool { @@ -50,7 +56,7 @@ impl ChatWidget { return; }; let next_tier = if self.current_service_tier() == Some(fast_tier.id.as_str()) { - None + Some(SERVICE_TIER_DEFAULT_REQUEST_VALUE.to_string()) } else { Some(fast_tier.id) }; @@ -59,7 +65,7 @@ impl ChatWidget { pub(crate) fn toggle_service_tier_from_ui(&mut self, command: ServiceTierCommand) { let next_tier = if self.current_service_tier() == Some(command.id.as_str()) { - None + Some(SERVICE_TIER_DEFAULT_REQUEST_VALUE.to_string()) } else { Some(command.id) }; @@ -98,9 +104,6 @@ impl ChatWidget { } fn set_service_tier_selection(&mut self, service_tier: Option) { - if service_tier.is_none() { - self.config.notices.fast_default_opt_out = Some(true); - } self.set_service_tier(service_tier.clone()); self.app_event_tx .send(AppEvent::CodexOp(AppCommand::override_turn_context( @@ -143,4 +146,12 @@ impl ChatWidget { .into_iter() .find(|tier| tier.name.eq_ignore_ascii_case(SPEED_TIER_FAST)) } + + pub(super) fn refresh_effective_service_tier(&mut self) { + self.effective_service_tier = service_tier_resolution::effective_service_tier( + &self.config, + self.current_model(), + &self.model_catalog.try_list_models().unwrap_or_default(), + ); + } } diff --git a/codex-rs/tui/src/chatwidget/settings.rs b/codex-rs/tui/src/chatwidget/settings.rs index 0434f7e386..accc750800 100644 --- a/codex-rs/tui/src/chatwidget/settings.rs +++ b/codex-rs/tui/src/chatwidget/settings.rs @@ -66,6 +66,7 @@ impl ChatWidget { } } if feature == Feature::FastMode { + self.refresh_effective_service_tier(); self.sync_service_tier_commands(); } if feature == Feature::Personality { @@ -238,6 +239,7 @@ impl ChatWidget { { mask.model = Some(model.to_string()); } + self.refresh_effective_service_tier(); self.refresh_model_dependent_surfaces(); } @@ -519,6 +521,7 @@ impl ChatWidget { settings.collaboration_mode.settings.model = settings.model; settings.collaboration_mode.settings.reasoning_effort = settings.effort; self.set_effective_collaboration_mode(settings.collaboration_mode); + self.refresh_effective_service_tier(); self.refresh_status_surfaces(); self.sync_service_tier_commands(); self.sync_personality_command_enabled(); diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__hooks_popup_shows_list_diagnostics.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__hooks_popup_shows_list_diagnostics.snap index 9a532f563d..99922ac630 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__hooks_popup_shows_list_diagnostics.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__hooks_popup_shows_list_diagnostics.snap @@ -18,6 +18,7 @@ expression: popup SessionStart 0 0 When a new session starts UserPromptSubmit 0 0 When the user submits a prompt SubagentStart 0 0 When a subagent is created + SubagentStop 0 0 Right before a subagent ends its turn Stop 0 0 Right before Codex ends its turn Press enter to view hooks; esc to close diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 77aa742c01..5d27e0ddc5 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -144,6 +144,7 @@ pub(super) use codex_protocol::approvals::GuardianUserAuthorization; pub(super) use codex_protocol::config_types::CollaborationMode; pub(super) use codex_protocol::config_types::ModeKind; pub(super) use codex_protocol::config_types::Personality; +pub(super) use codex_protocol::config_types::SERVICE_TIER_DEFAULT_REQUEST_VALUE; pub(super) use codex_protocol::config_types::ServiceTier; pub(super) use codex_protocol::models::ActivePermissionProfile; pub(super) use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_WORKSPACE; diff --git a/codex-rs/tui/src/chatwidget/tests/helpers.rs b/codex-rs/tui/src/chatwidget/tests/helpers.rs index 3bd0030465..63487f18b9 100644 --- a/codex-rs/tui/src/chatwidget/tests/helpers.rs +++ b/codex-rs/tui/src/chatwidget/tests/helpers.rs @@ -246,15 +246,14 @@ pub(crate) fn set_chatgpt_auth(chat: &mut ChatWidget) { } fn test_model_info(slug: &str, priority: i32, supports_fast_mode: bool) -> ModelInfo { - let service_tiers = if supports_fast_mode { - vec![json!({ + let mut service_tiers = Vec::new(); + if supports_fast_mode { + service_tiers.push(json!({ "id": ServiceTier::Fast.request_value(), "name": "fast", "description": "Fastest inference with increased plan usage" - })] - } else { - Vec::new() - }; + })); + } serde_json::from_value(json!({ "slug": slug, "display_name": slug, @@ -267,6 +266,7 @@ fn test_model_info(slug: &str, priority: i32, supports_fast_mode: bool) -> Model "priority": priority, "additional_speed_tiers": [], "service_tiers": service_tiers, + "default_service_tier": null, "availability_nux": null, "upgrade": null, "base_instructions": "base instructions", @@ -1572,6 +1572,7 @@ fn hook_event_label(event_name: codex_app_server_protocol::HookEventName) -> &'s codex_app_server_protocol::HookEventName::SessionStart => "SessionStart", codex_app_server_protocol::HookEventName::UserPromptSubmit => "UserPromptSubmit", codex_app_server_protocol::HookEventName::SubagentStart => "SubagentStart", + codex_app_server_protocol::HookEventName::SubagentStop => "SubagentStop", codex_app_server_protocol::HookEventName::Stop => "Stop", } } diff --git a/codex-rs/tui/src/chatwidget/tests/history_replay.rs b/codex-rs/tui/src/chatwidget/tests/history_replay.rs index a7ec121ded..58f99231f3 100644 --- a/codex-rs/tui/src/chatwidget/tests/history_replay.rs +++ b/codex-rs/tui/src/chatwidget/tests/history_replay.rs @@ -859,6 +859,7 @@ async fn replayed_in_progress_mcp_tool_call_stays_active() { status: codex_app_server_protocol::McpToolCallStatus::InProgress, arguments: json!({"action": "wait"}), mcp_app_resource_uri: None, + plugin_id: None, result: None, error: None, duration_ms: None, diff --git a/codex-rs/tui/src/chatwidget/tests/popups_and_settings.rs b/codex-rs/tui/src/chatwidget/tests/popups_and_settings.rs index 2a25415c03..09d911ad16 100644 --- a/codex-rs/tui/src/chatwidget/tests/popups_and_settings.rs +++ b/codex-rs/tui/src/chatwidget/tests/popups_and_settings.rs @@ -2279,6 +2279,7 @@ async fn model_picker_hides_show_in_picker_false_models_from_cache() { supports_personality: false, additional_speed_tiers: Vec::new(), service_tiers: Vec::new(), + default_service_tier: None, is_default: false, upgrade: None, show_in_picker, @@ -2500,6 +2501,7 @@ async fn single_reasoning_option_skips_selection() { supports_personality: false, additional_speed_tiers: Vec::new(), service_tiers: Vec::new(), + default_service_tier: None, is_default: false, upgrade: None, show_in_picker: true, diff --git a/codex-rs/tui/src/chatwidget/tests/slash_commands.rs b/codex-rs/tui/src/chatwidget/tests/slash_commands.rs index c8c0f60584..74d965ae5c 100644 --- a/codex-rs/tui/src/chatwidget/tests/slash_commands.rs +++ b/codex-rs/tui/src/chatwidget/tests/slash_commands.rs @@ -91,8 +91,19 @@ fn next_add_to_history_event(rx: &mut tokio::sync::mpsc::UnboundedReceiver {} + other => panic!("expected Op::UserTurn with default service tier override, got {other:?}"), + } +} + #[tokio::test] async fn queued_fast_slash_applies_before_next_queued_message() { let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(Some("gpt-5.4")).await; @@ -2194,18 +2246,20 @@ async fn user_turn_sends_standard_override_after_fast_is_turned_off() { events.iter().any(|event| matches!( event, AppEvent::CodexOp(Op::OverrideTurnContext { - service_tier: Some(None), + service_tier: Some(Some(service_tier)), .. - }) + }) if service_tier == SERVICE_TIER_DEFAULT_REQUEST_VALUE )), - "expected fast-mode off override app event; events: {events:?}" + "expected fast-mode off default service tier app event; events: {events:?}" ); assert!( events.iter().any(|event| matches!( event, - AppEvent::PersistServiceTierSelection { service_tier: None } + AppEvent::PersistServiceTierSelection { + service_tier: Some(service_tier) + } if service_tier == SERVICE_TIER_DEFAULT_REQUEST_VALUE )), - "expected fast-mode opt-out persistence app event; events: {events:?}" + "expected default service tier persistence app event; events: {events:?}" ); chat.bottom_pane @@ -2214,10 +2268,10 @@ async fn user_turn_sends_standard_override_after_fast_is_turned_off() { match next_submit_op(&mut op_rx) { Op::UserTurn { - service_tier: Some(None), + service_tier: Some(Some(service_tier)), .. - } => {} - other => panic!("expected Op::UserTurn with standard service tier override, got {other:?}"), + } if service_tier == SERVICE_TIER_DEFAULT_REQUEST_VALUE => {} + other => panic!("expected Op::UserTurn with default service tier override, got {other:?}"), } } diff --git a/codex-rs/tui/src/config_update.rs b/codex-rs/tui/src/config_update.rs index cac79f648e..f3dc0dc5fc 100644 --- a/codex-rs/tui/src/config_update.rs +++ b/codex-rs/tui/src/config_update.rs @@ -13,6 +13,7 @@ use codex_app_server_protocol::MergeStrategy; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::SkillsConfigWriteParams; use codex_app_server_protocol::SkillsConfigWriteResponse; +use codex_protocol::config_types::SERVICE_TIER_DEFAULT_REQUEST_VALUE; use codex_utils_absolute_path::AbsolutePathBuf; use color_eyre::eyre::Result; use color_eyre::eyre::WrapErr; @@ -75,26 +76,22 @@ pub(crate) fn build_service_tier_selection_edits( let service_tier_edit = service_tier.map_or_else( || clear_config_value(profile_scoped_key_path(profile, "service_tier")), |service_tier| { - let config_value = + let config_value = if service_tier == SERVICE_TIER_DEFAULT_REQUEST_VALUE { + SERVICE_TIER_DEFAULT_REQUEST_VALUE + } else { match codex_protocol::config_types::ServiceTier::from_request_value(service_tier) { Some(codex_protocol::config_types::ServiceTier::Fast) => "fast", Some(codex_protocol::config_types::ServiceTier::Flex) => "flex", None => service_tier, - }; + } + }; replace_config_value( profile_scoped_key_path(profile, "service_tier"), serde_json::json!(config_value), ) }, ); - let mut edits = vec![service_tier_edit]; - if service_tier.is_none() { - edits.push(replace_config_value( - "notice.fast_default_opt_out", - serde_json::json!(true), - )); - } - edits + vec![service_tier_edit] } pub(crate) async fn write_config_batch( diff --git a/codex-rs/tui/src/history_cell/hook_cell.rs b/codex-rs/tui/src/history_cell/hook_cell.rs index 824fdc1de8..6a4e8498d9 100644 --- a/codex-rs/tui/src/history_cell/hook_cell.rs +++ b/codex-rs/tui/src/history_cell/hook_cell.rs @@ -721,6 +721,7 @@ fn hook_event_label(event_name: HookEventName) -> &'static str { HookEventName::SessionStart => "SessionStart", HookEventName::UserPromptSubmit => "UserPromptSubmit", HookEventName::SubagentStart => "SubagentStart", + HookEventName::SubagentStop => "SubagentStop", HookEventName::Stop => "Stop", } } diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 40cd121c71..cbd19702bf 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -164,6 +164,7 @@ mod render; mod resize_reflow_cap; mod resume_picker; mod selection_list; +mod service_tier_resolution; mod session_log; mod session_resume; mod session_state; diff --git a/codex-rs/tui/src/service_tier_resolution.rs b/codex-rs/tui/src/service_tier_resolution.rs new file mode 100644 index 0000000000..1e65fd3fb0 --- /dev/null +++ b/codex-rs/tui/src/service_tier_resolution.rs @@ -0,0 +1,64 @@ +use crate::legacy_core::config::Config; +use codex_features::Feature; +use codex_protocol::config_types::SERVICE_TIER_DEFAULT_REQUEST_VALUE; +use codex_protocol::openai_models::ModelPreset; + +pub(crate) fn configured_service_tier(config: &Config) -> Option { + config.service_tier.clone().or_else(|| { + (config.notices.fast_default_opt_out == Some(true)) + .then(|| SERVICE_TIER_DEFAULT_REQUEST_VALUE.to_string()) + }) +} + +pub(crate) fn effective_service_tier( + config: &Config, + model: &str, + models: &[ModelPreset], +) -> Option { + if !config.features.enabled(Feature::FastMode) { + return None; + } + + let configured = configured_service_tier(config); + let Some(preset) = models.iter().find(|preset| preset.model == model) else { + return configured; + }; + + match configured.as_deref() { + Some(service_tier) if service_tier == SERVICE_TIER_DEFAULT_REQUEST_VALUE => configured, + Some(service_tier) if model_supports_service_tier(preset, service_tier) => configured, + Some(_) => None, + None => preset + .default_service_tier + .clone() + .filter(|service_tier| model_supports_service_tier(preset, service_tier)), + } +} + +pub(crate) fn service_tier_update_for_core( + config: &Config, + model: &str, + models: &[ModelPreset], +) -> Option> { + if !config.features.enabled(Feature::FastMode) { + return None; + } + + let effective = effective_service_tier(config, model, models); + if let Some(service_tier) = effective { + return Some(Some(service_tier)); + } + + if !models.iter().any(|preset| preset.model == model) { + return None; + } + + Some(Some(SERVICE_TIER_DEFAULT_REQUEST_VALUE.to_string())) +} + +pub(crate) fn model_supports_service_tier(model: &ModelPreset, service_tier: &str) -> bool { + model + .service_tiers + .iter() + .any(|tier| tier.id == service_tier) +} diff --git a/codex-rs/windows-sandbox-rs/BUILD.bazel b/codex-rs/windows-sandbox-rs/BUILD.bazel index e3f0112a85..31dbd3d24c 100644 --- a/codex-rs/windows-sandbox-rs/BUILD.bazel +++ b/codex-rs/windows-sandbox-rs/BUILD.bazel @@ -3,8 +3,4 @@ load("//:defs.bzl", "codex_rust_crate") codex_rust_crate( name = "windows-sandbox-rs", crate_name = "codex_windows_sandbox", - build_script_data = [ - "Cargo.toml", - "codex-windows-sandbox-setup.manifest", - ], ) diff --git a/codex-rs/windows-sandbox-rs/Cargo.toml b/codex-rs/windows-sandbox-rs/Cargo.toml index 31e563f4a8..3b00b40ae8 100644 --- a/codex-rs/windows-sandbox-rs/Cargo.toml +++ b/codex-rs/windows-sandbox-rs/Cargo.toml @@ -1,5 +1,4 @@ [package] -build = "build.rs" edition.workspace = true license.workspace = true name = "codex-windows-sandbox" @@ -93,6 +92,3 @@ version = "0.52" [dev-dependencies] pretty_assertions = { workspace = true } - -[build-dependencies] -winres = "0.1" diff --git a/codex-rs/windows-sandbox-rs/build.rs b/codex-rs/windows-sandbox-rs/build.rs deleted file mode 100644 index 3aca5b7e3e..0000000000 --- a/codex-rs/windows-sandbox-rs/build.rs +++ /dev/null @@ -1,15 +0,0 @@ -fn main() { - if std::env::var_os("RULES_RUST_BAZEL_BUILD_SCRIPT_RUNNER").is_some() - && matches!(std::env::var("CARGO_CFG_TARGET_ENV").as_deref(), Ok("gnu")) - { - // The Windows Bazel lint/test lane targets `windows-gnullvm`, where - // `winres` can emit a `resource` link directive without a usable - // archive in `OUT_DIR`. Skip embedding the manifest there; Cargo's - // normal MSVC builds still compile it. - return; - } - - let mut res = winres::WindowsResource::new(); - res.set_manifest_file("codex-windows-sandbox-setup.manifest"); - let _ = res.compile(); -} diff --git a/codex-rs/windows-sandbox-rs/codex-windows-sandbox-setup.manifest b/codex-rs/windows-sandbox-rs/codex-windows-sandbox-setup.manifest deleted file mode 100644 index 14807962f8..0000000000 --- a/codex-rs/windows-sandbox-rs/codex-windows-sandbox-setup.manifest +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/codex-rs/windows-sandbox-rs/src/elevated_impl.rs b/codex-rs/windows-sandbox-rs/src/elevated_impl.rs index dd343a22ce..f8a059918a 100644 --- a/codex-rs/windows-sandbox-rs/src/elevated_impl.rs +++ b/codex-rs/windows-sandbox-rs/src/elevated_impl.rs @@ -1,3 +1,4 @@ +use codex_protocol::models::PermissionProfile; use codex_utils_absolute_path::AbsolutePathBuf; use std::collections::HashMap; use std::path::Path; @@ -20,8 +21,26 @@ pub struct ElevatedSandboxCaptureRequest<'a> { pub deny_write_paths_override: &'a [AbsolutePathBuf], } +pub struct ElevatedSandboxProfileCaptureRequest<'a> { + pub permission_profile: &'a PermissionProfile, + pub permission_profile_cwd: &'a Path, + pub codex_home: &'a Path, + pub command: Vec, + pub cwd: &'a Path, + pub env_map: HashMap, + pub timeout_ms: Option, + pub use_private_desktop: bool, + pub proxy_enforced: bool, + pub read_roots_override: Option<&'a [PathBuf]>, + pub read_roots_include_platform_defaults: bool, + pub write_roots_override: Option<&'a [PathBuf]>, + pub deny_read_paths_override: &'a [AbsolutePathBuf], + pub deny_write_paths_override: &'a [AbsolutePathBuf], +} + mod windows_impl { use super::ElevatedSandboxCaptureRequest; + use super::ElevatedSandboxProfileCaptureRequest; use crate::acl::allow_null_device; use crate::cap::load_or_create_cap_sids; use crate::cap::workspace_write_cap_sid_for_root; @@ -37,7 +56,6 @@ mod windows_impl { use crate::logging::log_failure; use crate::logging::log_start; use crate::logging::log_success; - use crate::policy::SandboxPolicy; use crate::policy::parse_policy; use crate::resolved_permissions::ResolvedWindowsSandboxPermissions; use crate::runner_client::spawn_runner_transport; @@ -54,12 +72,12 @@ mod windows_impl { /// Launches the command runner under the sandbox user and captures its output. #[allow(clippy::too_many_arguments)] - pub fn run_windows_sandbox_capture( - request: ElevatedSandboxCaptureRequest<'_>, + pub fn run_windows_sandbox_capture_for_permission_profile( + request: ElevatedSandboxProfileCaptureRequest<'_>, ) -> Result { - let ElevatedSandboxCaptureRequest { - policy_json_or_preset, - sandbox_policy_cwd, + let ElevatedSandboxProfileCaptureRequest { + permission_profile, + permission_profile_cwd, codex_home, command, cwd, @@ -73,6 +91,10 @@ mod windows_impl { deny_read_paths_override, deny_write_paths_override, } = request; + let permissions = ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_cwd( + permission_profile, + permission_profile_cwd, + )?; let deny_read_paths_override = deny_read_paths_override .iter() .map(AbsolutePathBuf::to_path_buf) @@ -81,11 +103,6 @@ mod windows_impl { .iter() .map(AbsolutePathBuf::to_path_buf) .collect::>(); - let policy = parse_policy(policy_json_or_preset)?; - let permissions = ResolvedWindowsSandboxPermissions::from_legacy_policy_for_cwd( - &policy, - sandbox_policy_cwd, - ); normalize_null_device_env(&mut env_map); ensure_non_interactive_pager(&mut env_map); inherit_path_env(&mut env_map); @@ -109,12 +126,6 @@ mod windows_impl { proxy_enforced, )?; // Build capability SID for ACL grants. - if matches!( - &policy, - SandboxPolicy::DangerFullAccess | SandboxPolicy::ExternalSandbox { .. } - ) { - anyhow::bail!("DangerFullAccess and ExternalSandbox are not supported for sandboxing") - } let caps = load_or_create_cap_sids(codex_home)?; let (sid_for_null, cap_sids) = if permissions.uses_write_capabilities_for_cwd(cwd, &env_map) { @@ -143,14 +154,12 @@ mod windows_impl { } (|| -> Result { - let permission_profile = - PermissionProfile::from_legacy_sandbox_policy_for_cwd(&policy, sandbox_policy_cwd); let spawn_request = SpawnRequest { command: command.clone(), cwd: cwd.to_path_buf(), env: env_map.clone(), - permission_profile, - permission_profile_cwd: sandbox_policy_cwd.to_path_buf(), + permission_profile: permission_profile.clone(), + permission_profile_cwd: permission_profile_cwd.to_path_buf(), codex_home: sandbox_base.clone(), real_codex_home: codex_home.to_path_buf(), cap_sids, @@ -210,6 +219,48 @@ mod windows_impl { })() } + /// Legacy policy-string adapter for callers that have not moved to permission profiles yet. + #[allow(clippy::too_many_arguments)] + pub fn run_windows_sandbox_capture( + request: ElevatedSandboxCaptureRequest<'_>, + ) -> Result { + let ElevatedSandboxCaptureRequest { + policy_json_or_preset, + sandbox_policy_cwd, + codex_home, + command, + cwd, + env_map, + timeout_ms, + use_private_desktop, + proxy_enforced, + read_roots_override, + read_roots_include_platform_defaults, + write_roots_override, + deny_read_paths_override, + deny_write_paths_override, + } = request; + let policy = parse_policy(policy_json_or_preset)?; + let permission_profile = + PermissionProfile::from_legacy_sandbox_policy_for_cwd(&policy, sandbox_policy_cwd); + run_windows_sandbox_capture_for_permission_profile(ElevatedSandboxProfileCaptureRequest { + permission_profile: &permission_profile, + permission_profile_cwd: sandbox_policy_cwd, + codex_home, + command, + cwd, + env_map, + timeout_ms, + use_private_desktop, + proxy_enforced, + read_roots_override, + read_roots_include_platform_defaults, + write_roots_override, + deny_read_paths_override, + deny_write_paths_override, + }) + } + #[cfg(test)] mod tests { use crate::policy::SandboxPolicy; @@ -242,10 +293,13 @@ mod windows_impl { #[cfg(target_os = "windows")] pub use windows_impl::run_windows_sandbox_capture; +#[cfg(target_os = "windows")] +pub use windows_impl::run_windows_sandbox_capture_for_permission_profile; #[cfg(not(target_os = "windows"))] mod stub { use super::ElevatedSandboxCaptureRequest; + use super::ElevatedSandboxProfileCaptureRequest; use anyhow::Result; use anyhow::bail; @@ -264,7 +318,17 @@ mod stub { ) -> Result { bail!("Windows sandbox is only available on Windows") } + + /// Stub implementation for non-Windows targets; sandboxing only works on Windows. + #[allow(clippy::too_many_arguments)] + pub fn run_windows_sandbox_capture_for_permission_profile( + _request: ElevatedSandboxProfileCaptureRequest<'_>, + ) -> Result { + bail!("Windows sandbox is only available on Windows") + } } #[cfg(not(target_os = "windows"))] pub use stub::run_windows_sandbox_capture; +#[cfg(not(target_os = "windows"))] +pub use stub::run_windows_sandbox_capture_for_permission_profile; diff --git a/codex-rs/windows-sandbox-rs/src/lib.rs b/codex-rs/windows-sandbox-rs/src/lib.rs index e3365a2c8f..43b3f71955 100644 --- a/codex-rs/windows-sandbox-rs/src/lib.rs +++ b/codex-rs/windows-sandbox-rs/src/lib.rs @@ -139,8 +139,12 @@ pub use dpapi::unprotect as dpapi_unprotect; #[cfg(target_os = "windows")] pub use elevated_impl::ElevatedSandboxCaptureRequest; #[cfg(target_os = "windows")] +pub use elevated_impl::ElevatedSandboxProfileCaptureRequest; +#[cfg(target_os = "windows")] pub use elevated_impl::run_windows_sandbox_capture as run_windows_sandbox_capture_elevated; #[cfg(target_os = "windows")] +pub use elevated_impl::run_windows_sandbox_capture_for_permission_profile as run_windows_sandbox_capture_for_permission_profile_elevated; +#[cfg(target_os = "windows")] pub use helper_materialization::resolve_current_exe_for_launch; #[cfg(target_os = "windows")] pub use hide_users::hide_current_user_profile_dir; @@ -258,6 +262,8 @@ pub use token::get_current_token_for_restriction; #[cfg(target_os = "windows")] pub use unified_exec::spawn_windows_sandbox_session_elevated; #[cfg(target_os = "windows")] +pub use unified_exec::spawn_windows_sandbox_session_elevated_for_permission_profile; +#[cfg(target_os = "windows")] pub use unified_exec::spawn_windows_sandbox_session_legacy; #[cfg(target_os = "windows")] pub use wfp::install_wfp_filters_for_account; diff --git a/codex-rs/windows-sandbox-rs/src/resolved_permissions.rs b/codex-rs/windows-sandbox-rs/src/resolved_permissions.rs index ba5a4ca615..dbb08b2115 100644 --- a/codex-rs/windows-sandbox-rs/src/resolved_permissions.rs +++ b/codex-rs/windows-sandbox-rs/src/resolved_permissions.rs @@ -41,8 +41,10 @@ pub fn token_mode_for_permission_profile( cwd: &Path, env_map: &HashMap, ) -> Result { - let permissions = - ResolvedWindowsSandboxPermissions::try_from_permission_profile(permission_profile)?; + let permissions = ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_cwd( + permission_profile, + cwd, + )?; if permissions.file_system.has_full_disk_write_access() { anyhow::bail!( "permission profile requests full-disk filesystem writes, which cannot be enforced by the Windows sandbox" @@ -82,6 +84,19 @@ impl ResolvedWindowsSandboxPermissions { }) } + /// Resolves a managed permission profile and binds symbolic `:workspace_roots` + /// entries to the permission root supplied by the caller. + pub fn try_from_permission_profile_for_cwd( + permission_profile: &PermissionProfile, + cwd: &Path, + ) -> Result { + let mut permissions = Self::try_from_permission_profile(permission_profile)?; + permissions.file_system = permissions + .file_system + .materialize_project_roots_with_cwd(cwd); + Ok(permissions) + } + pub(crate) fn should_apply_network_block(&self) -> bool { !self.network.is_enabled() } @@ -259,6 +274,43 @@ mod tests { ); } + #[test] + fn permission_profile_workspace_root_stays_bound_to_profile_cwd() { + let tmp = TempDir::new().expect("tempdir"); + let profile_cwd = tmp.path().join("workspace"); + let command_cwd = profile_cwd.join("subdir"); + std::fs::create_dir_all(&command_cwd).expect("create command cwd"); + + let permission_profile = PermissionProfile::Managed { + file_system: ManagedFileSystemPermissions::Restricted { + entries: vec![FileSystemSandboxEntry { + path: FileSystemPath::Special { + value: FileSystemSpecialPath::project_roots(/*subpath*/ None), + }, + access: FileSystemAccessMode::Write, + }], + glob_scan_max_depth: None, + }, + network: NetworkSandboxPolicy::Restricted, + }; + let permissions = ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_cwd( + &permission_profile, + &profile_cwd, + ) + .expect("managed permission profile"); + + let roots = permissions + .writable_roots_for_cwd(&command_cwd, &HashMap::new()) + .into_iter() + .map(|root| root.root) + .collect::>(); + + assert_eq!( + roots, + vec![dunce::canonicalize(&profile_cwd).expect("canonical profile cwd")] + ); + } + #[test] fn token_mode_for_profile_without_writable_roots_uses_readonly_capability() { let tmp = TempDir::new().expect("tempdir"); diff --git a/codex-rs/windows-sandbox-rs/src/spawn_prep.rs b/codex-rs/windows-sandbox-rs/src/spawn_prep.rs index f4f0779742..f16e964308 100644 --- a/codex-rs/windows-sandbox-rs/src/spawn_prep.rs +++ b/codex-rs/windows-sandbox-rs/src/spawn_prep.rs @@ -44,13 +44,13 @@ pub(crate) struct SpawnContext { pub(crate) policy: SandboxPolicy, pub(crate) permissions: ResolvedWindowsSandboxPermissions, pub(crate) current_dir: PathBuf, - pub(crate) sandbox_base: PathBuf, pub(crate) logs_base_dir: Option, pub(crate) uses_write_capabilities: bool, } pub(crate) struct ElevatedSpawnContext { - pub(crate) common: SpawnContext, + pub(crate) sandbox_base: PathBuf, + pub(crate) logs_base_dir: Option, pub(crate) sandbox_creds: SandboxCreds, pub(crate) cap_sids: Vec, } @@ -109,7 +109,7 @@ fn prepare_spawn_context_common( ensure_codex_home_exists(codex_home)?; let sandbox_base = codex_home.join(".sandbox"); std::fs::create_dir_all(&sandbox_base)?; - let logs_base_dir = Some(sandbox_base.clone()); + let logs_base_dir = Some(sandbox_base); log_start(command, logs_base_dir.as_deref()); let permissions = @@ -120,7 +120,6 @@ fn prepare_spawn_context_common( policy, permissions, current_dir: cwd.to_path_buf(), - sandbox_base, logs_base_dir, uses_write_capabilities, }) @@ -362,9 +361,8 @@ pub(crate) fn apply_legacy_session_acl_rules( } #[allow(clippy::too_many_arguments)] -pub(crate) fn prepare_elevated_spawn_context( - policy_json_or_preset: &str, - sandbox_policy_cwd: &Path, +pub(crate) fn prepare_elevated_spawn_context_for_permissions( + permissions: ResolvedWindowsSandboxPermissions, codex_home: &Path, cwd: &Path, env_map: &mut HashMap, @@ -375,33 +373,33 @@ pub(crate) fn prepare_elevated_spawn_context( deny_read_paths_override: &[PathBuf], deny_write_paths_override: &[PathBuf], ) -> Result { - let common = prepare_spawn_context_common( - policy_json_or_preset, - sandbox_policy_cwd, - codex_home, - cwd, - env_map, - command, - SpawnPrepOptions { - inherit_path: true, - add_git_safe_directory: true, - }, - )?; + normalize_null_device_env(env_map); + ensure_non_interactive_pager(env_map); + inherit_path_env(env_map); + inject_git_safe_directory(env_map, cwd); + + // Use a temp-based log dir that the sandbox user can write. + let sandbox_base = codex_home.join(".sandbox"); + ensure_codex_home_exists(&sandbox_base)?; + let logs_base_dir = Some(sandbox_base.clone()); + log_start(command, logs_base_dir.as_deref()); + + let uses_write_capabilities = permissions.uses_write_capabilities_for_cwd(cwd, env_map); let AllowDenyPaths { allow, deny } = - compute_allow_paths_for_permissions(&common.permissions, &common.current_dir, env_map); + compute_allow_paths_for_permissions(&permissions, cwd, env_map); let write_roots: Vec = allow.into_iter().collect(); let deny_write_paths: Vec = deny.into_iter().collect(); - let computed_write_roots_override = if common.uses_write_capabilities { + let computed_write_roots_override = if uses_write_capabilities { Some(write_roots.as_slice()) } else { None }; let write_roots_for_setup = write_roots_override.or(computed_write_roots_override); - let effective_write_roots = if common.uses_write_capabilities { + let effective_write_roots = if uses_write_capabilities { effective_write_roots_for_permissions( - &common.permissions, - &common.current_dir, + &permissions, + cwd, env_map, codex_home, write_roots_for_setup, @@ -409,13 +407,13 @@ pub(crate) fn prepare_elevated_spawn_context( } else { Vec::new() }; - let setup_write_roots_override = if common.uses_write_capabilities { + let setup_write_roots_override = if uses_write_capabilities { Some(effective_write_roots.as_slice()) } else { write_roots_override }; let sandbox_creds = require_logon_sandbox_creds( - &common.permissions, + &permissions, cwd, env_map, codex_home, @@ -431,7 +429,7 @@ pub(crate) fn prepare_elevated_spawn_context( /*proxy_enforced*/ false, )?; let caps = load_or_create_cap_sids(codex_home)?; - let (psid_to_use, cap_sids) = if common.uses_write_capabilities { + let (psid_to_use, cap_sids) = if uses_write_capabilities { let cap_sids = root_capability_sids(codex_home, cwd, effective_write_roots)? .into_iter() .map(|root_sid| root_sid.sid_str) @@ -452,7 +450,8 @@ pub(crate) fn prepare_elevated_spawn_context( } Ok(ElevatedSpawnContext { - common, + sandbox_base, + logs_base_dir, sandbox_creds, cap_sids, }) diff --git a/codex-rs/windows-sandbox-rs/src/unified_exec/backends/elevated.rs b/codex-rs/windows-sandbox-rs/src/unified_exec/backends/elevated.rs index 352226644d..1e13e45cc0 100644 --- a/codex-rs/windows-sandbox-rs/src/unified_exec/backends/elevated.rs +++ b/codex-rs/windows-sandbox-rs/src/unified_exec/backends/elevated.rs @@ -8,8 +8,10 @@ use crate::ipc_framed::FramedMessage; use crate::ipc_framed::IPC_PROTOCOL_VERSION; use crate::ipc_framed::Message; use crate::ipc_framed::SpawnRequest; +use crate::policy::parse_policy; +use crate::resolved_permissions::ResolvedWindowsSandboxPermissions; use crate::runner_client::spawn_runner_transport; -use crate::spawn_prep::prepare_elevated_spawn_context; +use crate::spawn_prep::prepare_elevated_spawn_context_for_permissions; use anyhow::Result; use codex_protocol::models::PermissionProfile; use codex_utils_absolute_path::AbsolutePathBuf; @@ -23,9 +25,9 @@ use tokio::sync::mpsc; use tokio::sync::oneshot; #[allow(clippy::too_many_arguments)] -pub(crate) async fn spawn_windows_sandbox_session_elevated( - policy_json_or_preset: &str, - sandbox_policy_cwd: &Path, +pub(crate) async fn spawn_windows_sandbox_session_elevated_for_permission_profile( + permission_profile: &PermissionProfile, + permission_profile_cwd: &Path, codex_home: &Path, command: Vec, cwd: &Path, @@ -48,9 +50,12 @@ pub(crate) async fn spawn_windows_sandbox_session_elevated( .iter() .map(AbsolutePathBuf::to_path_buf) .collect::>(); - let elevated = prepare_elevated_spawn_context( - policy_json_or_preset, - sandbox_policy_cwd, + let permissions = ResolvedWindowsSandboxPermissions::try_from_permission_profile_for_cwd( + permission_profile, + permission_profile_cwd, + )?; + let elevated = prepare_elevated_spawn_context_for_permissions( + permissions, codex_home, cwd, &mut env_map, @@ -62,17 +67,13 @@ pub(crate) async fn spawn_windows_sandbox_session_elevated( &deny_write_paths_override, )?; - let permission_profile = PermissionProfile::from_legacy_sandbox_policy_for_cwd( - &elevated.common.policy, - sandbox_policy_cwd, - ); let spawn_request = SpawnRequest { command: command.clone(), cwd: cwd.to_path_buf(), env: env_map.clone(), - permission_profile, - permission_profile_cwd: sandbox_policy_cwd.to_path_buf(), - codex_home: elevated.common.sandbox_base.clone(), + permission_profile: permission_profile.clone(), + permission_profile_cwd: permission_profile_cwd.to_path_buf(), + codex_home: elevated.sandbox_base.clone(), real_codex_home: codex_home.to_path_buf(), cap_sids: elevated.cap_sids.clone(), timeout_ms, @@ -83,7 +84,7 @@ pub(crate) async fn spawn_windows_sandbox_session_elevated( let codex_home = codex_home.to_path_buf(); let cwd = cwd.to_path_buf(); let sandbox_creds = elevated.sandbox_creds.clone(); - let logs_base_dir = elevated.common.logs_base_dir.clone(); + let logs_base_dir = elevated.logs_base_dir.clone(); let transport = tokio::task::spawn_blocking(move || -> Result<_> { spawn_runner_transport( &codex_home, @@ -144,3 +145,44 @@ pub(crate) async fn spawn_windows_sandbox_session_elevated( stdin_open, )) } + +#[allow(clippy::too_many_arguments)] +pub(crate) async fn spawn_windows_sandbox_session_elevated( + policy_json_or_preset: &str, + sandbox_policy_cwd: &Path, + codex_home: &Path, + command: Vec, + cwd: &Path, + env_map: HashMap, + timeout_ms: Option, + read_roots_override: Option<&[PathBuf]>, + read_roots_include_platform_defaults: bool, + write_roots_override: Option<&[PathBuf]>, + deny_read_paths_override: &[AbsolutePathBuf], + deny_write_paths_override: &[AbsolutePathBuf], + tty: bool, + stdin_open: bool, + use_private_desktop: bool, +) -> Result { + let policy = parse_policy(policy_json_or_preset)?; + let permission_profile = + PermissionProfile::from_legacy_sandbox_policy_for_cwd(&policy, sandbox_policy_cwd); + spawn_windows_sandbox_session_elevated_for_permission_profile( + &permission_profile, + sandbox_policy_cwd, + codex_home, + command, + cwd, + env_map, + timeout_ms, + read_roots_override, + read_roots_include_platform_defaults, + write_roots_override, + deny_read_paths_override, + deny_write_paths_override, + tty, + stdin_open, + use_private_desktop, + ) + .await +} diff --git a/codex-rs/windows-sandbox-rs/src/unified_exec/mod.rs b/codex-rs/windows-sandbox-rs/src/unified_exec/mod.rs index adb653b6fe..ceb4bd03b6 100644 --- a/codex-rs/windows-sandbox-rs/src/unified_exec/mod.rs +++ b/codex-rs/windows-sandbox-rs/src/unified_exec/mod.rs @@ -10,6 +10,7 @@ mod backends; use anyhow::Result; +use codex_protocol::models::PermissionProfile; use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_pty::SpawnedProcess; use std::collections::HashMap; @@ -48,6 +49,44 @@ pub async fn spawn_windows_sandbox_session_legacy( .await } +#[allow(clippy::too_many_arguments)] +pub async fn spawn_windows_sandbox_session_elevated_for_permission_profile( + permission_profile: &PermissionProfile, + permission_profile_cwd: &Path, + codex_home: &Path, + command: Vec, + cwd: &Path, + env_map: HashMap, + timeout_ms: Option, + read_roots_override: Option<&[PathBuf]>, + read_roots_include_platform_defaults: bool, + write_roots_override: Option<&[PathBuf]>, + deny_read_paths_override: &[AbsolutePathBuf], + deny_write_paths_override: &[AbsolutePathBuf], + tty: bool, + stdin_open: bool, + use_private_desktop: bool, +) -> Result { + backends::elevated::spawn_windows_sandbox_session_elevated_for_permission_profile( + permission_profile, + permission_profile_cwd, + codex_home, + command, + cwd, + env_map, + timeout_ms, + read_roots_override, + read_roots_include_platform_defaults, + write_roots_override, + deny_read_paths_override, + deny_write_paths_override, + tty, + stdin_open, + use_private_desktop, + ) + .await +} + #[allow(clippy::too_many_arguments)] pub async fn spawn_windows_sandbox_session_elevated( policy_json_or_preset: &str,