Merge branch 'main' into codex/hook-name-description

This commit is contained in:
Abhinav
2026-06-17 20:56:37 -07:00
committed by GitHub
180 changed files with 6099 additions and 2286 deletions
+3 -3
View File
@@ -31,11 +31,11 @@ register_toolchains("@llvm//toolchain:all")
osx = use_extension("@llvm//extensions:osx.bzl", "osx")
osx.from_archive(
sha256 = "1bde70c0b1c2ab89ff454acbebf6741390d7b7eb149ca2a3ca24cc9203a408b7",
strip_prefix = "Payload/Library/Developer/CommandLineTools/SDKs/MacOSX26.4.sdk",
sha256 = "5f044578cd78a3a9b9c965a42d56bad609ee5d252e1d4e6aa7c42fc3f35fee7b",
strip_prefix = "Payload/Library/Developer/CommandLineTools/SDKs/MacOSX26.5.sdk",
type = "pkg",
urls = [
"https://swcdn.apple.com/content/downloads/32/53/047-96692-A_OAHIHT53YB/ybtshxmrcju8m2qvw3w5elr4rajtg1x3y3/CLTools_macOSNMOS_SDK.pkg",
"https://swcdn.apple.com/content/downloads/09/08/047-91568-A_Y1CFZWQCD4/4xekpyz43i26dbp4enxfro8eb1q7wiujh5/CLTools_macOSNMOS_SDK.pkg",
],
)
osx.frameworks(names = [
@@ -9,7 +9,11 @@ use crate::events::CodexCommandExecutionEventParams;
use crate::events::CodexCommandExecutionEventRequest;
use crate::events::CodexCompactionEventRequest;
use crate::events::CodexHookRunEventRequest;
use crate::events::CodexOnboardingExternalAgentImportFailureEventRequest;
use crate::events::CodexOnboardingExternalAgentImportFailureMetadata;
use crate::events::CodexPluginEventRequest;
use crate::events::CodexPluginInstallFailedEventRequest;
use crate::events::CodexPluginInstallFailedMetadata;
use crate::events::CodexPluginUsedEventRequest;
use crate::events::CodexReviewEventParams;
use crate::events::CodexReviewEventRequest;
@@ -51,10 +55,13 @@ use crate::facts::CompactionStatus;
use crate::facts::CompactionStrategy;
use crate::facts::CompactionTrigger;
use crate::facts::CustomAnalyticsFact;
use crate::facts::ExternalAgentConfigImportCompletedInput;
use crate::facts::ExternalAgentConfigImportFailureInput;
use crate::facts::HookRunFact;
use crate::facts::HookRunInput;
use crate::facts::InputError;
use crate::facts::InvocationType;
use crate::facts::PluginInstallFailedInput;
use crate::facts::PluginState;
use crate::facts::PluginStateChangedInput;
use crate::facts::PluginUsedInput;
@@ -178,6 +185,7 @@ fn sample_thread_with_metadata(
model_provider: "openai".to_string(),
created_at: 1,
updated_at: 2,
recency_at: Some(2),
status: AppServerThreadStatus::Idle,
path: None,
cwd: test_path_buf("/tmp").abs(),
@@ -3053,6 +3061,36 @@ fn plugin_management_event_serializes_expected_shape() {
);
}
#[test]
fn plugin_install_failed_event_serializes_expected_shape() {
let event = TrackEventRequest::PluginInstallFailed(CodexPluginInstallFailedEventRequest {
event_type: "codex_plugin_install_failed",
event_params: CodexPluginInstallFailedMetadata {
plugin: codex_plugin_metadata(sample_plugin_metadata()),
error_type: "store_io".to_string(),
},
});
let payload = serde_json::to_value(&event).expect("serialize plugin install failed event");
assert_eq!(
payload,
json!({
"event_type": "codex_plugin_install_failed",
"event_params": {
"plugin_id": "sample@test",
"plugin_name": "sample",
"marketplace_name": "test",
"has_skills": true,
"mcp_server_count": 2,
"connector_ids": ["calendar", "drive"],
"product_client_id": originator().value,
"error_type": "store_io"
}
})
);
}
#[test]
fn plugin_management_event_can_use_remote_plugin_id_override() {
let mut plugin = sample_plugin_metadata();
@@ -3420,6 +3458,190 @@ async fn reducer_ingests_plugin_state_changed_fact() {
);
}
#[tokio::test]
async fn reducer_ingests_plugin_install_failed_fact() {
let mut reducer = AnalyticsReducer::default();
let mut events = Vec::new();
reducer
.ingest(
AnalyticsFact::Custom(CustomAnalyticsFact::PluginInstallFailed(
PluginInstallFailedInput {
plugin: sample_plugin_metadata(),
error_type: "invalid_plugin".to_string(),
},
)),
&mut events,
)
.await;
let payload = serde_json::to_value(&events).expect("serialize events");
assert_eq!(
payload,
json!([{
"event_type": "codex_plugin_install_failed",
"event_params": {
"plugin_id": "sample@test",
"plugin_name": "sample",
"marketplace_name": "test",
"has_skills": true,
"mcp_server_count": 2,
"connector_ids": ["calendar", "drive"],
"product_client_id": originator().value,
"error_type": "invalid_plugin"
}
}])
);
}
#[tokio::test]
async fn reducer_ingests_plugin_install_failed_fact_without_detail() {
let mut reducer = AnalyticsReducer::default();
let mut events = Vec::new();
let mut plugin = PluginTelemetryMetadata::from_plugin_id(
&PluginId::parse("unknown@openai-curated-remote").expect("valid plugin id"),
);
plugin.remote_plugin_id = Some("plugins~Plugin_00000000000000000000000000000000".to_string());
reducer
.ingest(
AnalyticsFact::Custom(CustomAnalyticsFact::PluginInstallFailed(
PluginInstallFailedInput {
plugin,
error_type: "remote_catalog_unexpected_status".to_string(),
},
)),
&mut events,
)
.await;
let payload = serde_json::to_value(&events).expect("serialize events");
assert_eq!(
payload,
json!([{
"event_type": "codex_plugin_install_failed",
"event_params": {
"plugin_id": "plugins~Plugin_00000000000000000000000000000000",
"plugin_name": "unknown",
"marketplace_name": "openai-curated-remote",
"has_skills": null,
"mcp_server_count": null,
"connector_ids": null,
"product_client_id": originator().value,
"error_type": "remote_catalog_unexpected_status"
}
}])
);
}
#[tokio::test]
async fn reducer_ingests_external_agent_config_import_completed_fact() {
let mut reducer = AnalyticsReducer::default();
let mut events = Vec::new();
reducer
.ingest(
AnalyticsFact::Custom(CustomAnalyticsFact::ExternalAgentConfigImportCompleted(
ExternalAgentConfigImportCompletedInput {
import_id: "import-1".to_string(),
source: "app_server".to_string(),
item_type: "PLUGINS".to_string(),
success_count: 2,
failed_count: 1,
},
)),
&mut events,
)
.await;
let payload = serde_json::to_value(&events).expect("serialize events");
assert_eq!(
payload,
json!([{
"event_type": "codex_onboarding_external_agent_import_complete",
"event_params": {
"import_id": "import-1",
"source": "app_server",
"type": "PLUGINS",
"success_count": 2,
"failed_count": 1,
"product_client_id": originator().value,
}
}])
);
}
#[test]
fn external_agent_config_import_failure_event_serializes_expected_shape() {
let event = TrackEventRequest::ExternalAgentConfigImportFailure(
CodexOnboardingExternalAgentImportFailureEventRequest {
event_type: "codex_onboarding_external_agent_import_failure",
event_params: CodexOnboardingExternalAgentImportFailureMetadata {
import_id: "import-1".to_string(),
source: "app_server".to_string(),
item_type: "SESSIONS".to_string(),
failure_stage: "session_missing".to_string(),
error_type: "session_missing".to_string(),
product_client_id: Some(originator().value),
},
},
);
let payload = serde_json::to_value(&event).expect("serialize import failure event");
assert_eq!(
payload,
json!({
"event_type": "codex_onboarding_external_agent_import_failure",
"event_params": {
"import_id": "import-1",
"source": "app_server",
"type": "SESSIONS",
"failure_stage": "session_missing",
"error_type": "session_missing",
"product_client_id": originator().value,
}
})
);
}
#[tokio::test]
async fn reducer_ingests_external_agent_config_import_failure_fact() {
let mut reducer = AnalyticsReducer::default();
let mut events = Vec::new();
reducer
.ingest(
AnalyticsFact::Custom(CustomAnalyticsFact::ExternalAgentConfigImportFailure(
ExternalAgentConfigImportFailureInput {
import_id: "import-1".to_string(),
source: "app_server".to_string(),
item_type: "SESSIONS".to_string(),
failure_stage: "session_missing".to_string(),
error_type: "session_missing".to_string(),
},
)),
&mut events,
)
.await;
let payload = serde_json::to_value(&events).expect("serialize events");
assert_eq!(
payload,
json!([{
"event_type": "codex_onboarding_external_agent_import_failure",
"event_params": {
"import_id": "import-1",
"source": "app_server",
"type": "SESSIONS",
"failure_stage": "session_missing",
"error_type": "session_missing",
"product_client_id": originator().value,
}
}])
);
}
#[test]
fn turn_event_serializes_expected_shape() {
let event = TrackEventRequest::TurnEvent(Box::new(CodexTurnEventRequest {
+30
View File
@@ -11,8 +11,11 @@ use crate::facts::AppMentionedInput;
use crate::facts::AppUsedInput;
use crate::facts::CodexGoalEvent;
use crate::facts::CustomAnalyticsFact;
use crate::facts::ExternalAgentConfigImportCompletedInput;
use crate::facts::ExternalAgentConfigImportFailureInput;
use crate::facts::HookRunFact;
use crate::facts::HookRunInput;
use crate::facts::PluginInstallFailedInput;
use crate::facts::PluginState;
use crate::facts::PluginStateChangedInput;
use crate::facts::SkillInvocation;
@@ -343,6 +346,33 @@ impl AnalyticsEventsClient {
));
}
pub fn track_plugin_install_failed(&self, plugin: PluginTelemetryMetadata, error_type: String) {
self.record_fact(AnalyticsFact::Custom(
CustomAnalyticsFact::PluginInstallFailed(PluginInstallFailedInput {
plugin,
error_type,
}),
));
}
pub fn track_external_agent_config_import_completed(
&self,
input: ExternalAgentConfigImportCompletedInput,
) {
self.record_fact(AnalyticsFact::Custom(
CustomAnalyticsFact::ExternalAgentConfigImportCompleted(input),
));
}
pub fn track_external_agent_config_import_failure(
&self,
input: ExternalAgentConfigImportFailureInput,
) {
self.record_fact(AnalyticsFact::Custom(
CustomAnalyticsFact::ExternalAgentConfigImportFailure(input),
));
}
pub fn track_plugin_uninstalled(&self, plugin: PluginTelemetryMetadata) {
self.record_fact(AnalyticsFact::Custom(
CustomAnalyticsFact::PluginStateChanged(PluginStateChangedInput {
+1
View File
@@ -285,6 +285,7 @@ fn sample_thread(thread_id: &str) -> Thread {
model_provider: "openai".to_string(),
created_at: 1,
updated_at: 2,
recency_at: Some(2),
status: AppServerThreadStatus::Idle,
path: None,
cwd: test_path_buf("/tmp").abs(),
+50
View File
@@ -83,6 +83,9 @@ pub(crate) enum TrackEventRequest {
PluginUninstalled(CodexPluginEventRequest),
PluginEnabled(CodexPluginEventRequest),
PluginDisabled(CodexPluginEventRequest),
PluginInstallFailed(CodexPluginInstallFailedEventRequest),
ExternalAgentConfigImportCompleted(CodexOnboardingExternalAgentImportCompleteEventRequest),
ExternalAgentConfigImportFailure(CodexOnboardingExternalAgentImportFailureEventRequest),
}
impl TrackEventRequest {
@@ -954,6 +957,53 @@ pub(crate) struct CodexPluginEventRequest {
pub(crate) event_params: CodexPluginMetadata,
}
#[derive(Serialize)]
pub(crate) struct CodexPluginInstallFailedMetadata {
#[serde(flatten)]
pub(crate) plugin: CodexPluginMetadata,
pub(crate) error_type: String,
}
#[derive(Serialize)]
pub(crate) struct CodexPluginInstallFailedEventRequest {
pub(crate) event_type: &'static str,
pub(crate) event_params: CodexPluginInstallFailedMetadata,
}
#[derive(Serialize)]
pub(crate) struct CodexOnboardingExternalAgentImportCompleteMetadata {
pub(crate) import_id: String,
pub(crate) source: String,
#[serde(rename = "type")]
pub(crate) item_type: String,
pub(crate) success_count: usize,
pub(crate) failed_count: usize,
pub(crate) product_client_id: Option<String>,
}
#[derive(Serialize)]
pub(crate) struct CodexOnboardingExternalAgentImportCompleteEventRequest {
pub(crate) event_type: &'static str,
pub(crate) event_params: CodexOnboardingExternalAgentImportCompleteMetadata,
}
#[derive(Serialize)]
pub(crate) struct CodexOnboardingExternalAgentImportFailureMetadata {
pub(crate) import_id: String,
pub(crate) source: String,
#[serde(rename = "type")]
pub(crate) item_type: String,
pub(crate) failure_stage: String,
pub(crate) error_type: String,
pub(crate) product_client_id: Option<String>,
}
#[derive(Serialize)]
pub(crate) struct CodexOnboardingExternalAgentImportFailureEventRequest {
pub(crate) event_type: &'static str,
pub(crate) event_params: CodexOnboardingExternalAgentImportFailureMetadata,
}
#[derive(Serialize)]
pub(crate) struct CodexPluginUsedEventRequest {
pub(crate) event_type: &'static str,
+24
View File
@@ -504,6 +504,9 @@ pub(crate) enum CustomAnalyticsFact {
HookRun(HookRunInput),
PluginUsed(PluginUsedInput),
PluginStateChanged(PluginStateChangedInput),
PluginInstallFailed(PluginInstallFailedInput),
ExternalAgentConfigImportCompleted(ExternalAgentConfigImportCompletedInput),
ExternalAgentConfigImportFailure(ExternalAgentConfigImportFailureInput),
}
pub(crate) struct SkillInvokedInput {
@@ -542,6 +545,27 @@ pub(crate) struct PluginStateChangedInput {
pub state: PluginState,
}
pub(crate) struct PluginInstallFailedInput {
pub plugin: PluginTelemetryMetadata,
pub error_type: String,
}
pub struct ExternalAgentConfigImportCompletedInput {
pub import_id: String,
pub source: String,
pub item_type: String,
pub success_count: usize,
pub failed_count: usize,
}
pub struct ExternalAgentConfigImportFailureInput {
pub import_id: String,
pub source: String,
pub item_type: String,
pub failure_stage: String,
pub error_type: String,
}
#[derive(Clone, Copy)]
pub(crate) enum PluginState {
Installed,
+2
View File
@@ -36,6 +36,8 @@ pub use facts::CompactionReason;
pub use facts::CompactionStatus;
pub use facts::CompactionStrategy;
pub use facts::CompactionTrigger;
pub use facts::ExternalAgentConfigImportCompletedInput;
pub use facts::ExternalAgentConfigImportFailureInput;
pub use facts::GoalEventKind;
pub use facts::HookRunFact;
pub use facts::InputError;
+75
View File
@@ -21,7 +21,13 @@ use crate::events::CodexImageGenerationEventParams;
use crate::events::CodexImageGenerationEventRequest;
use crate::events::CodexMcpToolCallEventParams;
use crate::events::CodexMcpToolCallEventRequest;
use crate::events::CodexOnboardingExternalAgentImportCompleteEventRequest;
use crate::events::CodexOnboardingExternalAgentImportCompleteMetadata;
use crate::events::CodexOnboardingExternalAgentImportFailureEventRequest;
use crate::events::CodexOnboardingExternalAgentImportFailureMetadata;
use crate::events::CodexPluginEventRequest;
use crate::events::CodexPluginInstallFailedEventRequest;
use crate::events::CodexPluginInstallFailedMetadata;
use crate::events::CodexPluginUsedEventRequest;
use crate::events::CodexReviewEventParams;
use crate::events::CodexReviewEventRequest;
@@ -66,7 +72,10 @@ use crate::facts::AppUsedInput;
use crate::facts::CodexCompactionEvent;
use crate::facts::CodexGoalEvent;
use crate::facts::CustomAnalyticsFact;
use crate::facts::ExternalAgentConfigImportCompletedInput;
use crate::facts::ExternalAgentConfigImportFailureInput;
use crate::facts::HookRunInput;
use crate::facts::PluginInstallFailedInput;
use crate::facts::PluginState;
use crate::facts::PluginStateChangedInput;
use crate::facts::PluginUsedInput;
@@ -511,6 +520,15 @@ impl AnalyticsReducer {
CustomAnalyticsFact::PluginStateChanged(input) => {
self.ingest_plugin_state_changed(input, out);
}
CustomAnalyticsFact::PluginInstallFailed(input) => {
self.ingest_plugin_install_failed(input, out);
}
CustomAnalyticsFact::ExternalAgentConfigImportCompleted(input) => {
self.ingest_external_agent_config_import_completed(input, out);
}
CustomAnalyticsFact::ExternalAgentConfigImportFailure(input) => {
self.ingest_external_agent_config_import_failure(input, out);
}
},
}
}
@@ -775,6 +793,63 @@ impl AnalyticsReducer {
});
}
fn ingest_plugin_install_failed(
&mut self,
input: PluginInstallFailedInput,
out: &mut Vec<TrackEventRequest>,
) {
let PluginInstallFailedInput { plugin, error_type } = input;
out.push(TrackEventRequest::PluginInstallFailed(
CodexPluginInstallFailedEventRequest {
event_type: "codex_plugin_install_failed",
event_params: CodexPluginInstallFailedMetadata {
plugin: codex_plugin_metadata(plugin),
error_type,
},
},
));
}
fn ingest_external_agent_config_import_completed(
&mut self,
input: ExternalAgentConfigImportCompletedInput,
out: &mut Vec<TrackEventRequest>,
) {
out.push(TrackEventRequest::ExternalAgentConfigImportCompleted(
CodexOnboardingExternalAgentImportCompleteEventRequest {
event_type: "codex_onboarding_external_agent_import_complete",
event_params: CodexOnboardingExternalAgentImportCompleteMetadata {
import_id: input.import_id,
source: input.source,
item_type: input.item_type,
success_count: input.success_count,
failed_count: input.failed_count,
product_client_id: Some(originator().value),
},
},
));
}
fn ingest_external_agent_config_import_failure(
&mut self,
input: ExternalAgentConfigImportFailureInput,
out: &mut Vec<TrackEventRequest>,
) {
out.push(TrackEventRequest::ExternalAgentConfigImportFailure(
CodexOnboardingExternalAgentImportFailureEventRequest {
event_type: "codex_onboarding_external_agent_import_failure",
event_params: CodexOnboardingExternalAgentImportFailureMetadata {
import_id: input.import_id,
source: input.source,
item_type: input.item_type,
failure_stage: input.failure_stage,
error_type: input.error_type,
product_client_id: Some(originator().value),
},
},
));
}
async fn ingest_response(
&mut self,
connection_id: u64,
+15 -47
View File
@@ -800,7 +800,7 @@
]
},
"includeHome": {
"description": "If true, include detection under the user's home (~/.claude, ~/.codex, etc.).",
"description": "If true, include detection under the user's home directory.",
"type": "boolean"
}
},
@@ -813,6 +813,13 @@
"$ref": "#/definitions/ExternalAgentConfigMigrationItem"
},
"type": "array"
},
"source": {
"description": "Source product that produced the migration items. Missing means unspecified.",
"type": [
"string",
"null"
]
}
},
"required": [
@@ -2282,13 +2289,6 @@
},
"type": "array"
},
"id": {
"type": [
"string",
"null"
],
"writeOnly": true
},
"metadata": {
"anyOf": [
{
@@ -2430,14 +2430,6 @@
"null"
]
},
"id": {
"description": "Legacy id field retained for compatibility with older payloads.",
"type": [
"string",
"null"
],
"writeOnly": true
},
"metadata": {
"anyOf": [
{
@@ -2475,13 +2467,6 @@
"call_id": {
"type": "string"
},
"id": {
"type": [
"string",
"null"
],
"writeOnly": true
},
"metadata": {
"anyOf": [
{
@@ -2530,13 +2515,6 @@
"execution": {
"type": "string"
},
"id": {
"type": [
"string",
"null"
],
"writeOnly": true
},
"metadata": {
"anyOf": [
{
@@ -2608,13 +2586,6 @@
"call_id": {
"type": "string"
},
"id": {
"type": [
"string",
"null"
],
"writeOnly": true
},
"input": {
"type": "string"
},
@@ -2751,13 +2722,6 @@
}
]
},
"id": {
"type": [
"string",
"null"
],
"writeOnly": true
},
"metadata": {
"anyOf": [
{
@@ -2791,7 +2755,11 @@
{
"properties": {
"id": {
"type": "string"
"description": "Existing provider ID retained on serialized history for compatibility.",
"type": [
"string",
"null"
]
},
"metadata": {
"anyOf": [
@@ -2824,7 +2792,6 @@
}
},
"required": [
"id",
"result",
"status",
"type"
@@ -4164,7 +4131,8 @@
"ThreadSortKey": {
"enum": [
"created_at",
"updated_at"
"updated_at",
"recency_at"
],
"type": "string"
},
@@ -3582,6 +3582,14 @@
"description": "Usually the first user message in the thread, if available.",
"type": "string"
},
"recencyAt": {
"description": "Unix timestamp (in seconds) used for thread recency ordering.",
"format": "int64",
"type": [
"integer",
"null"
]
},
"sessionId": {
"description": "Session id shared by threads that belong to the same session tree.",
"type": "string"
@@ -9119,7 +9119,7 @@
]
},
"includeHome": {
"description": "If true, include detection under the user's home (~/.claude, ~/.codex, etc.).",
"description": "If true, include detection under the user's home directory.",
"type": "boolean"
}
},
@@ -9282,6 +9282,13 @@
"$ref": "#/definitions/v2/ExternalAgentConfigMigrationItem"
},
"type": "array"
},
"source": {
"description": "Source product that produced the migration items. Missing means unspecified.",
"type": [
"string",
"null"
]
}
},
"required": [
@@ -14784,13 +14791,6 @@
},
"type": "array"
},
"id": {
"type": [
"string",
"null"
],
"writeOnly": true
},
"metadata": {
"anyOf": [
{
@@ -14932,14 +14932,6 @@
"null"
]
},
"id": {
"description": "Legacy id field retained for compatibility with older payloads.",
"type": [
"string",
"null"
],
"writeOnly": true
},
"metadata": {
"anyOf": [
{
@@ -14977,13 +14969,6 @@
"call_id": {
"type": "string"
},
"id": {
"type": [
"string",
"null"
],
"writeOnly": true
},
"metadata": {
"anyOf": [
{
@@ -15032,13 +15017,6 @@
"execution": {
"type": "string"
},
"id": {
"type": [
"string",
"null"
],
"writeOnly": true
},
"metadata": {
"anyOf": [
{
@@ -15110,13 +15088,6 @@
"call_id": {
"type": "string"
},
"id": {
"type": [
"string",
"null"
],
"writeOnly": true
},
"input": {
"type": "string"
},
@@ -15253,13 +15224,6 @@
}
]
},
"id": {
"type": [
"string",
"null"
],
"writeOnly": true
},
"metadata": {
"anyOf": [
{
@@ -15293,7 +15257,11 @@
{
"properties": {
"id": {
"type": "string"
"description": "Existing provider ID retained on serialized history for compatibility.",
"type": [
"string",
"null"
]
},
"metadata": {
"anyOf": [
@@ -15326,7 +15294,6 @@
}
},
"required": [
"id",
"result",
"status",
"type"
@@ -16645,6 +16612,14 @@
"description": "Usually the first user message in the thread, if available.",
"type": "string"
},
"recencyAt": {
"description": "Unix timestamp (in seconds) used for thread recency ordering.",
"format": "int64",
"type": [
"integer",
"null"
]
},
"sessionId": {
"description": "Session id shared by threads that belong to the same session tree.",
"type": "string"
@@ -18904,7 +18879,8 @@
"ThreadSortKey": {
"enum": [
"created_at",
"updated_at"
"updated_at",
"recency_at"
],
"type": "string"
},
@@ -5404,7 +5404,7 @@
]
},
"includeHome": {
"description": "If true, include detection under the user's home (~/.claude, ~/.codex, etc.).",
"description": "If true, include detection under the user's home directory.",
"type": "boolean"
}
},
@@ -5567,6 +5567,13 @@
"$ref": "#/definitions/ExternalAgentConfigMigrationItem"
},
"type": "array"
},
"source": {
"description": "Source product that produced the migration items. Missing means unspecified.",
"type": [
"string",
"null"
]
}
},
"required": [
@@ -11229,13 +11236,6 @@
},
"type": "array"
},
"id": {
"type": [
"string",
"null"
],
"writeOnly": true
},
"metadata": {
"anyOf": [
{
@@ -11377,14 +11377,6 @@
"null"
]
},
"id": {
"description": "Legacy id field retained for compatibility with older payloads.",
"type": [
"string",
"null"
],
"writeOnly": true
},
"metadata": {
"anyOf": [
{
@@ -11422,13 +11414,6 @@
"call_id": {
"type": "string"
},
"id": {
"type": [
"string",
"null"
],
"writeOnly": true
},
"metadata": {
"anyOf": [
{
@@ -11477,13 +11462,6 @@
"execution": {
"type": "string"
},
"id": {
"type": [
"string",
"null"
],
"writeOnly": true
},
"metadata": {
"anyOf": [
{
@@ -11555,13 +11533,6 @@
"call_id": {
"type": "string"
},
"id": {
"type": [
"string",
"null"
],
"writeOnly": true
},
"input": {
"type": "string"
},
@@ -11698,13 +11669,6 @@
}
]
},
"id": {
"type": [
"string",
"null"
],
"writeOnly": true
},
"metadata": {
"anyOf": [
{
@@ -11738,7 +11702,11 @@
{
"properties": {
"id": {
"type": "string"
"description": "Existing provider ID retained on serialized history for compatibility.",
"type": [
"string",
"null"
]
},
"metadata": {
"anyOf": [
@@ -11771,7 +11739,6 @@
}
},
"required": [
"id",
"result",
"status",
"type"
@@ -14445,6 +14412,14 @@
"description": "Usually the first user message in the thread, if available.",
"type": "string"
},
"recencyAt": {
"description": "Unix timestamp (in seconds) used for thread recency ordering.",
"format": "int64",
"type": [
"integer",
"null"
]
},
"sessionId": {
"description": "Session id shared by threads that belong to the same session tree.",
"type": "string"
@@ -16704,7 +16679,8 @@
"ThreadSortKey": {
"enum": [
"created_at",
"updated_at"
"updated_at",
"recency_at"
],
"type": "string"
},
@@ -12,7 +12,7 @@
]
},
"includeHome": {
"description": "If true, include detection under the user's home (~/.claude, ~/.codex, etc.).",
"description": "If true, include detection under the user's home directory.",
"type": "boolean"
}
},
@@ -184,6 +184,13 @@
"$ref": "#/definitions/ExternalAgentConfigMigrationItem"
},
"type": "array"
},
"source": {
"description": "Source product that produced the migration items. Missing means unspecified.",
"type": [
"string",
"null"
]
}
},
"required": [
@@ -377,13 +377,6 @@
},
"type": "array"
},
"id": {
"type": [
"string",
"null"
],
"writeOnly": true
},
"metadata": {
"anyOf": [
{
@@ -525,14 +518,6 @@
"null"
]
},
"id": {
"description": "Legacy id field retained for compatibility with older payloads.",
"type": [
"string",
"null"
],
"writeOnly": true
},
"metadata": {
"anyOf": [
{
@@ -570,13 +555,6 @@
"call_id": {
"type": "string"
},
"id": {
"type": [
"string",
"null"
],
"writeOnly": true
},
"metadata": {
"anyOf": [
{
@@ -625,13 +603,6 @@
"execution": {
"type": "string"
},
"id": {
"type": [
"string",
"null"
],
"writeOnly": true
},
"metadata": {
"anyOf": [
{
@@ -703,13 +674,6 @@
"call_id": {
"type": "string"
},
"id": {
"type": [
"string",
"null"
],
"writeOnly": true
},
"input": {
"type": "string"
},
@@ -846,13 +810,6 @@
}
]
},
"id": {
"type": [
"string",
"null"
],
"writeOnly": true
},
"metadata": {
"anyOf": [
{
@@ -886,7 +843,11 @@
{
"properties": {
"id": {
"type": "string"
"description": "Existing provider ID retained on serialized history for compatibility.",
"type": [
"string",
"null"
]
},
"metadata": {
"anyOf": [
@@ -919,7 +880,6 @@
}
},
"required": [
"id",
"result",
"status",
"type"
@@ -1055,6 +1055,14 @@
"description": "Usually the first user message in the thread, if available.",
"type": "string"
},
"recencyAt": {
"description": "Unix timestamp (in seconds) used for thread recency ordering.",
"format": "int64",
"type": [
"integer",
"null"
]
},
"sessionId": {
"description": "Session id shared by threads that belong to the same session tree.",
"type": "string"
@@ -24,7 +24,8 @@
"ThreadSortKey": {
"enum": [
"created_at",
"updated_at"
"updated_at",
"recency_at"
],
"type": "string"
},
@@ -870,6 +870,14 @@
"description": "Usually the first user message in the thread, if available.",
"type": "string"
},
"recencyAt": {
"description": "Unix timestamp (in seconds) used for thread recency ordering.",
"format": "int64",
"type": [
"integer",
"null"
]
},
"sessionId": {
"description": "Session id shared by threads that belong to the same session tree.",
"type": "string"
@@ -870,6 +870,14 @@
"description": "Usually the first user message in the thread, if available.",
"type": "string"
},
"recencyAt": {
"description": "Unix timestamp (in seconds) used for thread recency ordering.",
"format": "int64",
"type": [
"integer",
"null"
]
},
"sessionId": {
"description": "Session id shared by threads that belong to the same session tree.",
"type": "string"
@@ -870,6 +870,14 @@
"description": "Usually the first user message in the thread, if available.",
"type": "string"
},
"recencyAt": {
"description": "Unix timestamp (in seconds) used for thread recency ordering.",
"format": "int64",
"type": [
"integer",
"null"
]
},
"sessionId": {
"description": "Session id shared by threads that belong to the same session tree.",
"type": "string"
@@ -448,13 +448,6 @@
},
"type": "array"
},
"id": {
"type": [
"string",
"null"
],
"writeOnly": true
},
"metadata": {
"anyOf": [
{
@@ -596,14 +589,6 @@
"null"
]
},
"id": {
"description": "Legacy id field retained for compatibility with older payloads.",
"type": [
"string",
"null"
],
"writeOnly": true
},
"metadata": {
"anyOf": [
{
@@ -641,13 +626,6 @@
"call_id": {
"type": "string"
},
"id": {
"type": [
"string",
"null"
],
"writeOnly": true
},
"metadata": {
"anyOf": [
{
@@ -696,13 +674,6 @@
"execution": {
"type": "string"
},
"id": {
"type": [
"string",
"null"
],
"writeOnly": true
},
"metadata": {
"anyOf": [
{
@@ -774,13 +745,6 @@
"call_id": {
"type": "string"
},
"id": {
"type": [
"string",
"null"
],
"writeOnly": true
},
"input": {
"type": "string"
},
@@ -917,13 +881,6 @@
}
]
},
"id": {
"type": [
"string",
"null"
],
"writeOnly": true
},
"metadata": {
"anyOf": [
{
@@ -957,7 +914,11 @@
{
"properties": {
"id": {
"type": "string"
"description": "Existing provider ID retained on serialized history for compatibility.",
"type": [
"string",
"null"
]
},
"metadata": {
"anyOf": [
@@ -990,7 +951,6 @@
}
},
"required": [
"id",
"result",
"status",
"type"
@@ -1055,6 +1055,14 @@
"description": "Usually the first user message in the thread, if available.",
"type": "string"
},
"recencyAt": {
"description": "Unix timestamp (in seconds) used for thread recency ordering.",
"format": "int64",
"type": [
"integer",
"null"
]
},
"sessionId": {
"description": "Session id shared by threads that belong to the same session tree.",
"type": "string"
@@ -870,6 +870,14 @@
"description": "Usually the first user message in the thread, if available.",
"type": "string"
},
"recencyAt": {
"description": "Unix timestamp (in seconds) used for thread recency ordering.",
"format": "int64",
"type": [
"integer",
"null"
]
},
"sessionId": {
"description": "Session id shared by threads that belong to the same session tree.",
"type": "string"
@@ -1055,6 +1055,14 @@
"description": "Usually the first user message in the thread, if available.",
"type": "string"
},
"recencyAt": {
"description": "Unix timestamp (in seconds) used for thread recency ordering.",
"format": "int64",
"type": [
"integer",
"null"
]
},
"sessionId": {
"description": "Session id shared by threads that belong to the same session tree.",
"type": "string"
@@ -870,6 +870,14 @@
"description": "Usually the first user message in the thread, if available.",
"type": "string"
},
"recencyAt": {
"description": "Unix timestamp (in seconds) used for thread recency ordering.",
"format": "int64",
"type": [
"integer",
"null"
]
},
"sessionId": {
"description": "Session id shared by threads that belong to the same session tree.",
"type": "string"
@@ -870,6 +870,14 @@
"description": "Usually the first user message in the thread, if available.",
"type": "string"
},
"recencyAt": {
"description": "Unix timestamp (in seconds) used for thread recency ordering.",
"format": "int64",
"type": [
"integer",
"null"
]
},
"sessionId": {
"description": "Session id shared by threads that belong to the same session tree.",
"type": "string"
@@ -16,4 +16,8 @@ export type ResponseItem = { "type": "message", role: string, content: Array<Con
/**
* Set when using the Responses API.
*/
call_id: string | null, status: LocalShellStatus, action: LocalShellAction, metadata?: ResponseItemMetadata, } | { "type": "function_call", name: string, namespace?: string, arguments: string, call_id: string, metadata?: ResponseItemMetadata, } | { "type": "tool_search_call", call_id: string | null, status?: string, execution: string, arguments: unknown, metadata?: ResponseItemMetadata, } | { "type": "function_call_output", call_id: string, output: FunctionCallOutputBody, metadata?: ResponseItemMetadata, } | { "type": "custom_tool_call", status?: string, call_id: string, name: string, input: string, metadata?: ResponseItemMetadata, } | { "type": "custom_tool_call_output", call_id: string, name?: string, output: FunctionCallOutputBody, metadata?: ResponseItemMetadata, } | { "type": "tool_search_output", call_id: string | null, status: string, execution: string, tools: unknown[], metadata?: ResponseItemMetadata, } | { "type": "web_search_call", status?: string, action?: WebSearchAction, metadata?: ResponseItemMetadata, } | { "type": "image_generation_call", id: string, status: string, revised_prompt?: string, result: string, metadata?: ResponseItemMetadata, } | { "type": "compaction", encrypted_content: string, metadata?: ResponseItemMetadata, } | { "type": "compaction_trigger", metadata?: ResponseItemMetadata, } | { "type": "context_compaction", encrypted_content?: string, metadata?: ResponseItemMetadata, } | { "type": "other" };
call_id: string | null, status: LocalShellStatus, action: LocalShellAction, metadata?: ResponseItemMetadata, } | { "type": "function_call", name: string, namespace?: string, arguments: string, call_id: string, metadata?: ResponseItemMetadata, } | { "type": "tool_search_call", call_id: string | null, status?: string, execution: string, arguments: unknown, metadata?: ResponseItemMetadata, } | { "type": "function_call_output", call_id: string, output: FunctionCallOutputBody, metadata?: ResponseItemMetadata, } | { "type": "custom_tool_call", status?: string, call_id: string, name: string, input: string, metadata?: ResponseItemMetadata, } | { "type": "custom_tool_call_output", call_id: string, name?: string, output: FunctionCallOutputBody, metadata?: ResponseItemMetadata, } | { "type": "tool_search_output", call_id: string | null, status: string, execution: string, tools: unknown[], metadata?: ResponseItemMetadata, } | { "type": "web_search_call", status?: string, action?: WebSearchAction, metadata?: ResponseItemMetadata, } | { "type": "image_generation_call",
/**
* Existing provider ID retained on serialized history for compatibility.
*/
id?: string, status: string, revised_prompt?: string, result: string, metadata?: ResponseItemMetadata, } | { "type": "compaction", encrypted_content: string, metadata?: ResponseItemMetadata, } | { "type": "compaction_trigger", metadata?: ResponseItemMetadata, } | { "type": "context_compaction", encrypted_content?: string, metadata?: ResponseItemMetadata, } | { "type": "other" };
@@ -4,7 +4,7 @@
export type ExternalAgentConfigDetectParams = {
/**
* If true, include detection under the user's home (~/.claude, ~/.codex, etc.).
* If true, include detection under the user's home directory.
*/
includeHome?: boolean,
/**
@@ -3,4 +3,8 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { ExternalAgentConfigMigrationItem } from "./ExternalAgentConfigMigrationItem";
export type ExternalAgentConfigImportParams = { migrationItems: Array<ExternalAgentConfigMigrationItem>, };
export type ExternalAgentConfigImportParams = { migrationItems: Array<ExternalAgentConfigMigrationItem>,
/**
* Source product that produced the migration items. Missing means unspecified.
*/
source?: string | null, };
@@ -41,6 +41,10 @@ createdAt: number,
* Unix timestamp (in seconds) when the thread was last updated.
*/
updatedAt: number,
/**
* Unix timestamp (in seconds) used for thread recency ordering.
*/
recencyAt: number | null,
/**
* Current runtime status for the thread.
*/
@@ -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 ThreadSortKey = "created_at" | "updated_at";
export type ThreadSortKey = "created_at" | "updated_at" | "recency_at";
@@ -2501,6 +2501,7 @@ mod tests {
model_provider: "openai".to_string(),
created_at: 1,
updated_at: 2,
recency_at: Some(3),
status: v2::ThreadStatus::Idle,
path: None,
cwd: cwd.clone(),
@@ -2544,6 +2545,7 @@ mod tests {
"modelProvider": "openai",
"createdAt": 1,
"updatedAt": 2,
"recencyAt": 3,
"status": {
"type": "idle"
},
@@ -3080,8 +3082,10 @@ mod tests {
request_id: RequestId::Integer(9),
params: v2::ThreadRealtimeStartParams {
architecture: Some(RealtimeConversationArchitecture::Avas),
client_managed_handoffs: Some(true),
codex_responses_as_items: None,
codex_response_item_prefix: None,
codex_response_handoff_prefix: Some("silent context".to_string()),
thread_id: "thr_123".to_string(),
model: Some("realtime-treatment-model".to_string()),
output_modality: RealtimeOutputModality::Audio,
@@ -3100,8 +3104,10 @@ mod tests {
"params": {
"architecture": "avas",
"threadId": "thr_123",
"clientManagedHandoffs": true,
"codexResponsesAsItems": null,
"codexResponseItemPrefix": null,
"codexResponseHandoffPrefix": "silent context",
"model": "realtime-treatment-model",
"outputModality": "audio",
"includeStartupContext": false,
@@ -3123,8 +3129,10 @@ mod tests {
request_id: RequestId::Integer(9),
params: v2::ThreadRealtimeStartParams {
architecture: None,
client_managed_handoffs: None,
codex_responses_as_items: None,
codex_response_item_prefix: None,
codex_response_handoff_prefix: None,
thread_id: "thr_123".to_string(),
model: None,
output_modality: RealtimeOutputModality::Audio,
@@ -3143,8 +3151,10 @@ mod tests {
"params": {
"architecture": null,
"threadId": "thr_123",
"clientManagedHandoffs": null,
"codexResponsesAsItems": null,
"codexResponseItemPrefix": null,
"codexResponseHandoffPrefix": null,
"model": null,
"outputModality": "audio",
"includeStartupContext": null,
@@ -3161,8 +3171,10 @@ mod tests {
request_id: RequestId::Integer(9),
params: v2::ThreadRealtimeStartParams {
architecture: None,
client_managed_handoffs: None,
codex_responses_as_items: None,
codex_response_item_prefix: None,
codex_response_handoff_prefix: None,
thread_id: "thr_123".to_string(),
model: None,
output_modality: RealtimeOutputModality::Audio,
@@ -3181,8 +3193,10 @@ mod tests {
"params": {
"architecture": null,
"threadId": "thr_123",
"clientManagedHandoffs": null,
"codexResponsesAsItems": null,
"codexResponseItemPrefix": null,
"codexResponseHandoffPrefix": null,
"model": null,
"outputModality": "audio",
"includeStartupContext": null,
@@ -3365,8 +3379,10 @@ mod tests {
request_id: RequestId::Integer(1),
params: v2::ThreadRealtimeStartParams {
architecture: None,
client_managed_handoffs: None,
codex_responses_as_items: None,
codex_response_item_prefix: None,
codex_response_handoff_prefix: None,
thread_id: "thr_123".to_string(),
model: None,
output_modality: RealtimeOutputModality::Audio,
@@ -651,7 +651,7 @@ pub struct ExternalAgentConfigDetectResponse {
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ExternalAgentConfigDetectParams {
/// If true, include detection under the user's home (~/.claude, ~/.codex, etc.).
/// If true, include detection under the user's home directory.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub include_home: bool,
/// Zero or more working directories to include for repo-scoped detection.
@@ -664,6 +664,9 @@ pub struct ExternalAgentConfigDetectParams {
#[ts(export_to = "v2/")]
pub struct ExternalAgentConfigImportParams {
pub migration_items: Vec<ExternalAgentConfigMigrationItem>,
/// Source product that produced the migration items. Missing means unspecified.
#[ts(optional = nullable)]
pub source: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
@@ -70,12 +70,21 @@ pub struct ThreadRealtimeStartParams {
/// Overrides the configured realtime architecture for this session only.
#[ts(optional = nullable)]
pub architecture: Option<RealtimeConversationArchitecture>,
/// Leaves Codex response handoffs to the client's explicit append calls instead of forwarding
/// them automatically. Defaults to false.
#[ts(optional = nullable)]
pub client_managed_handoffs: Option<bool>,
/// Sends automatic Codex responses as realtime conversation items instead of handoff appends.
#[ts(optional = nullable)]
pub codex_responses_as_items: Option<bool>,
/// Optional prefix added to automatic Codex response items when `codexResponsesAsItems` is true.
#[ts(optional = nullable)]
pub codex_response_item_prefix: Option<String>,
/// Optional prefix added to automatic V1 Codex commentary sent with
/// `conversation.handoff.append` when `codexResponsesAsItems` is not true. Final answers are
/// sent without the prefix.
#[ts(optional = nullable)]
pub codex_response_handoff_prefix: Option<String>,
/// Overrides the configured realtime model for this session only.
#[ts(optional = nullable)]
pub model: Option<String>,
@@ -174,6 +174,7 @@ fn thread_resume_response_round_trips_initial_turns_page() {
model_provider: "openai".to_string(),
created_at: 1,
updated_at: 1,
recency_at: Some(1),
status: ThreadStatus::Idle,
path: None,
cwd: absolute_path("tmp"),
@@ -375,6 +376,7 @@ fn external_agent_config_import_params_accept_legacy_plugin_details() {
..Default::default()
}),
}],
source: None,
}
);
}
@@ -3600,6 +3602,7 @@ fn thread_lifecycle_responses_default_missing_optional_fields() {
assert_eq!(start.instruction_sources, Vec::<AbsolutePathBuf>::new());
assert_eq!(start.thread.parent_thread_id, None);
assert_eq!(start.thread.recency_at, None);
assert_eq!(resume.instruction_sources, Vec::<AbsolutePathBuf>::new());
assert_eq!(fork.instruction_sources, Vec::<AbsolutePathBuf>::new());
assert_eq!(start.active_permission_profile, None);
@@ -3608,6 +3611,14 @@ fn thread_lifecycle_responses_default_missing_optional_fields() {
assert_eq!(fork.active_permission_profile, None);
}
#[test]
fn thread_recency_sort_key_serializes_as_snake_case() {
assert_eq!(
serde_json::to_value(ThreadSortKey::RecencyAt).expect("sort key should serialize"),
json!("recency_at")
);
}
#[test]
fn turn_start_params_preserve_explicit_null_service_tier() {
let params: TurnStartParams = serde_json::from_value(json!({
@@ -1086,6 +1086,7 @@ pub enum ThreadSourceKind {
pub enum ThreadSortKey {
CreatedAt,
UpdatedAt,
RecencyAt,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, JsonSchema, TS)]
@@ -152,6 +152,9 @@ pub struct Thread {
/// Unix timestamp (in seconds) when the thread was last updated.
#[ts(type = "number")]
pub updated_at: i64,
/// Unix timestamp (in seconds) used for thread recency ordering.
#[ts(type = "number | null")]
pub recency_at: Option<i64>,
/// Current runtime status for the thread.
pub status: ThreadStatus,
/// [UNSTABLE] Path to the thread on disk.
+14 -6
View File
@@ -165,7 +165,7 @@ Example with notification opt-out:
- `thread/inject_items` — append raw Responses API items to a loaded thread’s model-visible history without starting a user turn; returns `{}` on success.
- `turn/steer` — add user input to an already in-flight regular turn without starting a new turn; returns the active `turnId` that accepted the input. `clientUserMessageId` is optional; when supplied, the corresponding `userMessage` item echoes it as `clientId`. Review and manual compaction turns reject `turn/steer`.
- `turn/interrupt` — request cancellation of an in-flight turn by `(thread_id, turn_id)`; success is an empty `{}` response and the turn finishes with `status: "interrupted"`.
- `thread/realtime/start` — start a thread-scoped realtime session (experimental); pass `outputModality: "text"` or `outputModality: "audio"` to choose model output, optionally pass `model` and `version` to override configured realtime selection for this session only, and pass `includeStartupContext: false` to omit Codex's generated startup context. By default, automatic Codex text follows the protocol's speakable output path. Pass `codexResponsesAsItems: true` to send automatic Codex responses as realtime conversation items instead, and optionally pass `codexResponseItemPrefix` to prepend experiment instructions to those items. Returns `{}` and streams `thread/realtime/*` notifications. Omit `transport` for the websocket transport, or pass `{ "type": "webrtc", "sdp": "..." }` to create a WebRTC session from a browser-generated SDP offer; the remote answer SDP is emitted as `thread/realtime/sdp`.
- `thread/realtime/start` — start a thread-scoped realtime session (experimental); pass `outputModality: "text"` or `outputModality: "audio"` to choose model output, optionally pass `model` and `version` to override configured realtime selection for this session only, and pass `includeStartupContext: false` to omit Codex's generated startup context. By default, automatic Codex text follows the protocol's speakable output path. Pass `clientManagedHandoffs: true` to disable automatic Codex response delivery so only the client's explicit append calls produce handoffs. Pass `codexResponsesAsItems: true` to send automatic Codex responses as realtime conversation items instead, and optionally pass `codexResponseItemPrefix` to prepend experiment instructions to those items. For V1 sessions, pass `codexResponseHandoffPrefix` while item mode is disabled to route automatic Codex commentary through `conversation.handoff.append` with that prefix; final answers remain unprefixed. Returns `{}` and streams `thread/realtime/*` notifications. Omit `transport` for the websocket transport, or pass `{ "type": "webrtc", "sdp": "..." }` to create a WebRTC session from a browser-generated SDP offer; the remote answer SDP is emitted as `thread/realtime/sdp`.
- `thread/realtime/appendAudio` — append an input audio chunk to the active realtime session (experimental); returns `{}`.
- `thread/realtime/appendText` — append text input to the active realtime session with a required `role` of `user` or `developer` (experimental); returns `{}`. Older clients that omit `role` default to `user`.
- `thread/realtime/appendSpeech` — append text that the realtime model should speak to the user (experimental); returns `{}`.
@@ -232,7 +232,7 @@ Example with notification opt-out:
- `feedback/upload` — submit a feedback report (classification + optional reason/logs, conversation_id, and optional `extraLogFiles` attachments array); returns the tracking thread id.
- `config/read` — fetch the effective config on disk after resolving config layering, including opaque `desktop` values stored in `config.toml`.
- `externalAgentConfig/detect` — detect migratable external-agent artifacts with `includeHome` and optional `cwds`; each detected item includes `cwd` (`null` for home), and plugin/session migration items may additionally include structured `details` grouping plugin ids or session metadata.
- `externalAgentConfig/import` — apply selected external-agent migration items by passing explicit `migrationItems` with `cwd` (`null` for home) and any plugin/session `details` returned by detect. Returns an `importId` used to correlate the completion notification. When a request includes migration items, the server emits `externalAgentConfig/import/completed` once after the full import finishes with type-level `itemResults` containing each migrated type's success count, error count, successes, and raw errors (immediately after the response when everything completed synchronously, or after background imports finish).
- `externalAgentConfig/import` — apply selected external-agent migration items by passing explicit `migrationItems` with `cwd` (`null` for home) and any plugin/session `details` returned by detect. Callers may pass `source` to identify the product that initiated the import; omitted or `null` means unspecified. The response acknowledges the synchronous import phase with an `importId`. Expected migration failures are reported as per-item failures rather than JSON-RPC errors, so the server still returns that `importId` and emits `externalAgentConfig/import/completed` with the same ID once all synchronous and background work finishes. The completion notification contains type-level `itemTypeResults` with successes and failures, including raw failure messages for the client to report separately.
- `config/value/write` — write a single config key/value to the user's config.toml on disk; dotted paths such as `desktop.someKey` use the same generic write surface.
- `config/batchWrite` — apply multiple config edits atomically to the user's config.toml on disk, with optional `reloadUserConfig: true` to hot-reload loaded threads, including multiple `desktop.*` edits.
- `configRequirements/read` — fetch loaded requirements constraints from `requirements.toml` and/or MDM (or `null` if none are configured), including allow-lists (`allowedApprovalPolicies`, `allowedSandboxModes`, `allowedWebSearchModes`), the layered permission-profile allow map (`allowedPermissionProfiles`), the managed permission-profile default (`defaultPermissions`), lifecycle hook lockdown (`allowManagedHooksOnly`), remote-control policy (`allowRemoteControl`; `false` force-disables remote control while `true` or `null` preserves existing behavior), computer use policy (`computerUse`), pinned feature values (`featureRequirements`), managed lifecycle hooks (`hooks`), `enforceResidency`, and `network` constraints such as canonical domain/socket permissions plus `managedAllowedDomainsOnly` and `dangerFullAccessDenylistOnly`.
@@ -364,7 +364,8 @@ Like `thread/resume`, experimental clients can pass `excludeTurns: true` to `thr
- `cursor` — opaque string from a prior response; omit for the first page.
- `limit` — server defaults to a reasonable page size if unset.
- `sortKey` — `created_at` (default) or `updated_at`.
- `sortKey` — `created_at` (default), `updated_at`, or `recency_at`.
- `recencyAt` is initialized when the thread is created and advances when a turn starts. Unlike `updatedAt`, background output and other persisted mutations do not advance it.
- `sortDirection` — `desc` (default) or `asc`.
- `modelProviders` — restrict results to specific providers; unset, null, or an empty array will include all providers.
- `sourceKinds` — restrict results to specific sources; omit or pass `[]` for interactive sessions only (`cli`, `vscode`).
@@ -386,8 +387,8 @@ Example:
} }
{ "id": 20, "result": {
"data": [
{ "id": "thr_a", "preview": "Create a TUI", "modelProvider": "openai", "createdAt": 1730831111, "updatedAt": 1730831111, "status": { "type": "notLoaded" }, "agentNickname": "Atlas", "agentRole": "explorer" },
{ "id": "thr_b", "preview": "Fix tests", "modelProvider": "openai", "createdAt": 1730750000, "updatedAt": 1730750000, "status": { "type": "notLoaded" } }
{ "id": "thr_a", "preview": "Create a TUI", "modelProvider": "openai", "createdAt": 1730831111, "updatedAt": 1730831111, "recencyAt": 1730831111, "status": { "type": "notLoaded" }, "agentNickname": "Atlas", "agentRole": "explorer" },
{ "id": "thr_b", "preview": "Fix tests", "modelProvider": "openai", "createdAt": 1730750000, "updatedAt": 1730750000, "recencyAt": 1730750000, "status": { "type": "notLoaded" } }
],
"nextCursor": "opaque-token-or-null",
"backwardsCursor": "opaque-token-or-null"
@@ -881,12 +882,19 @@ Clients may also pass `model` and `version` on `thread/realtime/start` to select
different realtime session configuration without changing thread or user config.
Pass `includeStartupContext: false` to skip Codex's startup context for this
session while still using the selected backend prompt.
Pass `clientManagedHandoffs: true` to suppress automatic Codex response handoffs
and items. The client can then choose which updates to deliver with
`thread/realtime/appendText` or `thread/realtime/appendSpeech`.
Pass `codexResponsesAsItems: true` to inject automatic Codex responses with
`conversation.item.create` instead of the protocol's default speakable output
path. When using that mode, `codexResponseItemPrefix` can prepend short
experiment instructions to each automatic Codex response item. Omit
`codexResponsesAsItems`, or pass `false`, to preserve the default speakable
behavior. Call
behavior. For V1 sessions, `codexResponseHandoffPrefix` instead routes automatic
Codex commentary through `conversation.handoff.append` and prepends the provided
text. Final answers remain unprefixed. Item mode takes precedence when
`codexResponsesAsItems` is true.
Call
`thread/realtime/appendText` to append app-provided realtime text items, or
`thread/realtime/appendSpeech` when the app decides a realtime update should be
spoken.
@@ -2261,6 +2261,7 @@ mod tests {
reasoning_effort: None,
created_at,
updated_at: created_at,
recency_at: created_at,
archived_at: None,
cwd: test_path_buf("/tmp").abs().into(),
cli_version: "0.0.0".to_string(),
+4
View File
@@ -237,6 +237,10 @@ impl CommandExecManager {
arg0,
..
} = exec_request;
// TODO(anp): Keep PathUri through the local command launch boundary.
let cwd = cwd
.to_abs_path()
.map_err(|err| invalid_request(format!("invalid command cwd: {err}")))?;
let stream_stdin = tty || stream_stdin;
let stream_stdout_stderr = tty || stream_stdout_stderr;
@@ -237,7 +237,7 @@ impl ExternalAgentConfigService {
pub(crate) async fn import(
&self,
migration_items: Vec<ExternalAgentConfigMigrationItem>,
) -> io::Result<ExternalAgentConfigImportOutcome> {
) -> ExternalAgentConfigImportOutcome {
let mut outcome = ExternalAgentConfigImportOutcome::default();
for migration_item in migration_items {
let item_type = migration_item.item_type;
@@ -413,17 +413,28 @@ impl ExternalAgentConfigService {
})(),
ExternalAgentConfigMigrationItemType::Sessions => Ok(()),
};
if let Err(err) = import_result {
if item_type == ExternalAgentConfigMigrationItemType::Plugins {
outcome.item_results.push(item_result);
continue;
}
return Err(err);
if let Err(err) = import_result
&& item_type != ExternalAgentConfigMigrationItemType::Plugins
{
let message = err.to_string();
let error_type = if message.contains("invalid existing config.toml") {
"invalid_existing_config"
} else {
"external_agent_config_import_error"
};
item_result.record_error(ExternalAgentConfigImportRawError {
item_type,
error_type: Some(error_type.to_string()),
failure_stage: "import_request_failed".to_string(),
message,
cwd: item_result.cwd.clone(),
source: None,
});
}
outcome.item_results.push(item_result);
}
Ok(outcome)
outcome
}
async fn detect_migrations(
@@ -561,8 +561,7 @@ async fn import_repo_migrates_mcp_hooks_commands_and_subagents() {
details: None,
},
])
.await
.expect("import");
.await;
let config: TomlValue = toml::from_str(
&fs::read_to_string(repo_root.join(".codex").join("config.toml")).expect("read config"),
@@ -724,8 +723,7 @@ url = "https://example.com/mixed-transport"
cwd: Some(repo_root.clone()),
details: None,
}])
.await
.expect("import");
.await;
assert_eq!(
fs::read_to_string(repo_root.join(".codex").join("config.toml")).expect("read config"),
@@ -838,8 +836,7 @@ async fn import_home_migrates_supported_config_fields_skills_and_agents_md() {
details: None,
},
])
.await
.expect("import");
.await;
assert_eq!(
fs::read_to_string(codex_home.join("AGENTS.md")).expect("read agents"),
@@ -894,8 +891,7 @@ async fn import_home_config_uses_local_settings_over_project_settings() {
cwd: None,
details: None,
}])
.await
.expect("import");
.await;
let config: TomlValue =
toml::from_str(&fs::read_to_string(codex_home.join("config.toml")).expect("read config"))
@@ -939,8 +935,7 @@ async fn import_home_config_ignores_invalid_local_settings() {
cwd: None,
details: None,
}])
.await
.expect("import");
.await;
assert_eq!(
fs::read_to_string(codex_home.join("config.toml")).expect("read config"),
@@ -965,8 +960,7 @@ async fn import_home_skips_empty_config_migration() {
cwd: None,
details: None,
}])
.await
.expect("import");
.await;
assert_eq!(
outcome.item_results,
@@ -1043,8 +1037,7 @@ async fn import_local_plugins_returns_completed_status() {
..Default::default()
}),
}])
.await
.expect("import");
.await;
assert_eq!(
outcome.pending_plugin_imports,
@@ -1104,8 +1097,7 @@ async fn import_git_plugins_returns_pending_async_status() {
..Default::default()
}),
}])
.await
.expect("import");
.await;
assert_eq!(
outcome.pending_plugin_imports,
@@ -1235,8 +1227,7 @@ async fn import_repo_agents_md_rewrites_terms_and_skips_non_empty_targets() {
details: None,
},
])
.await
.expect("import");
.await;
assert_eq!(
outcome.item_results,
@@ -1302,8 +1293,7 @@ async fn import_repo_agents_md_overwrites_empty_targets() {
cwd: Some(repo_root.clone()),
details: None,
}])
.await
.expect("import");
.await;
assert_eq!(
outcome.item_results,
@@ -1403,8 +1393,7 @@ async fn import_repo_hooks_preserves_disabled_codex_hooks_feature() {
cwd: Some(repo_root.clone()),
details: None,
}])
.await
.expect("import");
.await;
assert_eq!(
outcome.item_results,
@@ -1481,8 +1470,7 @@ async fn import_repo_mcp_uses_home_settings_toggles_when_repo_settings_missing()
cwd: Some(repo_root.clone()),
details: None,
}])
.await
.expect("import");
.await;
assert_eq!(
outcome.item_results,
@@ -1559,8 +1547,7 @@ async fn import_repo_mcp_uses_local_settings_toggles_over_project_settings() {
cwd: Some(repo_root.clone()),
details: None,
}])
.await
.expect("import");
.await;
let config: TomlValue = toml::from_str(
&fs::read_to_string(repo_root.join(".codex").join("config.toml")).expect("read config"),
@@ -1607,8 +1594,7 @@ async fn import_repo_mcp_ignores_invalid_home_settings_when_repo_settings_missin
cwd: Some(repo_root.clone()),
details: None,
}])
.await
.expect("import");
.await;
let config: TomlValue = toml::from_str(
&fs::read_to_string(repo_root.join(".codex").join("config.toml")).expect("read config"),
@@ -1649,8 +1635,7 @@ async fn import_repo_uses_non_empty_external_agent_agents_source() {
cwd: Some(repo_root.clone()),
details: None,
}])
.await
.expect("import");
.await;
assert_eq!(
fs::read_to_string(repo_root.join("AGENTS.md")).expect("read target"),
@@ -1683,8 +1668,7 @@ async fn import_continues_after_failed_migration_item() {
details: None,
},
])
.await
.expect("import continues");
.await;
assert_eq!(
fs::read_to_string(repo_root.join("AGENTS.md")).expect("read target"),
+2 -1
View File
@@ -515,7 +515,7 @@ impl MessageProcessor {
outgoing.clone(),
config_manager.clone(),
thread_manager.clone(),
analytics_events_client,
analytics_events_client.clone(),
);
let external_agent_config_processor =
ExternalAgentConfigRequestProcessor::new(ExternalAgentConfigRequestProcessorArgs {
@@ -525,6 +525,7 @@ impl MessageProcessor {
config_manager: config_manager.clone(),
config_processor: config_processor.clone(),
state_db,
analytics_events_client,
arg0_paths,
codex_home: config.codex_home.to_path_buf(),
});
@@ -15,6 +15,9 @@ use crate::config_manager::ConfigManager;
use crate::error_code::internal_error;
use crate::outgoing_message::ConnectionRequestId;
use crate::outgoing_message::OutgoingMessageSender;
use codex_analytics::AnalyticsEventsClient;
use codex_analytics::ExternalAgentConfigImportCompletedInput;
use codex_analytics::ExternalAgentConfigImportFailureInput;
use codex_app_server_protocol::CommandMigration;
use codex_app_server_protocol::ExternalAgentConfigDetectParams;
use codex_app_server_protocol::ExternalAgentConfigDetectResponse;
@@ -57,6 +60,7 @@ pub(crate) struct ExternalAgentConfigRequestProcessor {
thread_manager: Arc<ThreadManager>,
config_processor: ConfigRequestProcessor,
state_db: Option<StateDbHandle>,
analytics_events_client: AnalyticsEventsClient,
}
pub(crate) struct ExternalAgentConfigRequestProcessorArgs {
@@ -66,6 +70,7 @@ pub(crate) struct ExternalAgentConfigRequestProcessorArgs {
pub(crate) config_manager: ConfigManager,
pub(crate) config_processor: ConfigRequestProcessor,
pub(crate) state_db: Option<StateDbHandle>,
pub(crate) analytics_events_client: AnalyticsEventsClient,
pub(crate) arg0_paths: Arg0DispatchPaths,
pub(crate) codex_home: PathBuf,
}
@@ -79,6 +84,7 @@ impl ExternalAgentConfigRequestProcessor {
config_manager,
config_processor,
state_db,
analytics_events_client,
arg0_paths,
codex_home,
} = args;
@@ -96,6 +102,7 @@ impl ExternalAgentConfigRequestProcessor {
thread_manager,
config_processor,
state_db,
analytics_events_client,
}
}
@@ -199,6 +206,7 @@ impl ExternalAgentConfigRequestProcessor {
params: ExternalAgentConfigImportParams,
) -> Result<(), JSONRPCErrorError> {
let import_id = Uuid::new_v4().to_string();
let analytics_source = params.source.clone().unwrap_or_default();
let needs_runtime_refresh = migration_items_need_runtime_refresh(&params.migration_items);
let has_migration_items = !params.migration_items.is_empty();
let has_plugin_imports = params.migration_items.iter().any(|item| {
@@ -209,7 +217,7 @@ impl ExternalAgentConfigRequestProcessor {
});
let (pending_session_imports, session_validation_result) =
self.validate_pending_session_imports(&params);
let import_outcome = self.import_external_agent_config(params).await?;
let import_outcome = self.import_external_agent_config(params).await;
if needs_runtime_refresh {
self.config_processor.handle_config_mutation().await;
}
@@ -242,7 +250,9 @@ impl ExternalAgentConfigRequestProcessor {
send_completed_import_notification(
&self.outgoing,
self.state_db.as_ref(),
&self.analytics_events_client,
import_id,
analytics_source,
&completed_item_results,
)
.await;
@@ -253,6 +263,7 @@ impl ExternalAgentConfigRequestProcessor {
let plugin_processor = self.clone();
let outgoing = Arc::clone(&self.outgoing);
let state_db = self.state_db.clone();
let analytics_events_client = self.analytics_events_client.clone();
let thread_manager = Arc::clone(&self.thread_manager);
let session_import_result = (!pending_session_imports.is_empty()).then(|| {
CoreImportItemResult::new(
@@ -324,7 +335,9 @@ impl ExternalAgentConfigRequestProcessor {
send_completed_import_notification(
&outgoing,
state_db.as_ref(),
&analytics_events_client,
import_id,
analytics_source,
&completed_item_results,
)
.await;
@@ -421,7 +434,7 @@ impl ExternalAgentConfigRequestProcessor {
async fn import_external_agent_config(
&self,
params: ExternalAgentConfigImportParams,
) -> Result<CoreImportOutcome, JSONRPCErrorError> {
) -> CoreImportOutcome {
self.migration_service
.import(
params
@@ -516,7 +529,6 @@ impl ExternalAgentConfigRequestProcessor {
.collect(),
)
.await
.map_err(|err| internal_error(err.to_string()))
}
async fn complete_pending_plugin_import(
@@ -551,10 +563,14 @@ async fn send_import_progress(
async fn send_completed_import_notification(
outgoing: &OutgoingMessageSender,
state_db: Option<&StateDbHandle>,
analytics_events_client: &AnalyticsEventsClient,
import_id: String,
analytics_source: String,
item_results: &[CoreImportItemResult],
) {
let notification = completed_notification(import_id, item_results);
log_completed_import_failures(&notification);
track_completed_import_notification(analytics_events_client, &analytics_source, &notification);
if let Some(state_db) = state_db
&& let Err(err) = record_completed_import_notification(state_db, &notification).await
{
@@ -571,6 +587,75 @@ async fn send_completed_import_notification(
.await;
}
fn log_completed_import_failures(notification: &ExternalAgentConfigImportCompletedNotification) {
for type_result in &notification.item_type_results {
for failure in &type_result.failures {
let error_type = import_failure_error_type(failure);
tracing::warn!(
import_id = %notification.import_id,
item_type = ?failure.item_type,
error_type = %error_type,
failure_stage = %failure.failure_stage,
cwd = ?failure.cwd,
source = ?failure.source,
error = %failure.message,
"external agent config migration item failed"
);
}
}
}
fn track_completed_import_notification(
analytics_events_client: &AnalyticsEventsClient,
analytics_source: &str,
notification: &ExternalAgentConfigImportCompletedNotification,
) {
for type_result in &notification.item_type_results {
let item_type = analytics_migration_item_type(type_result.item_type).to_string();
analytics_events_client.track_external_agent_config_import_completed(
ExternalAgentConfigImportCompletedInput {
import_id: notification.import_id.clone(),
source: analytics_source.to_string(),
item_type: item_type.clone(),
success_count: type_result.successes.len(),
failed_count: type_result.failures.len(),
},
);
for failure in &type_result.failures {
analytics_events_client.track_external_agent_config_import_failure(
ExternalAgentConfigImportFailureInput {
import_id: notification.import_id.clone(),
source: analytics_source.to_string(),
item_type: item_type.clone(),
failure_stage: failure.failure_stage.clone(),
error_type: import_failure_error_type(failure),
},
);
}
}
}
fn import_failure_error_type(failure: &ProtocolImportFailure) -> String {
failure
.error_type
.clone()
.unwrap_or_else(|| failure.failure_stage.clone())
}
fn analytics_migration_item_type(item_type: ExternalAgentConfigMigrationItemType) -> &'static str {
match item_type {
ExternalAgentConfigMigrationItemType::AgentsMd => "AGENTS_MD",
ExternalAgentConfigMigrationItemType::Config => "CONFIG",
ExternalAgentConfigMigrationItemType::Skills => "SKILLS",
ExternalAgentConfigMigrationItemType::Plugins => "PLUGINS",
ExternalAgentConfigMigrationItemType::McpServerConfig => "MCP_SERVER_CONFIG",
ExternalAgentConfigMigrationItemType::Subagents => "SUBAGENTS",
ExternalAgentConfigMigrationItemType::Hooks => "HOOKS",
ExternalAgentConfigMigrationItemType::Commands => "COMMANDS",
ExternalAgentConfigMigrationItemType::Sessions => "SESSIONS",
}
}
async fn record_completed_import_notification(
state_db: &StateDbHandle,
notification: &ExternalAgentConfigImportCompletedNotification,
@@ -18,9 +18,12 @@ use codex_core_plugins::remote::REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETP
use codex_core_plugins::remote::RemoteAppTemplateUnavailableReason;
use codex_core_plugins::remote::is_valid_remote_plugin_id;
use codex_core_plugins::remote::validate_remote_plugin_id;
use codex_core_plugins::remote_bundle::RemotePluginBundleInstallError;
use codex_mcp::McpOAuthLoginSupport;
use codex_mcp::oauth_login_support;
use codex_mcp::should_retry_without_scopes;
use codex_plugin::PluginId;
use codex_plugin::PluginTelemetryMetadata;
use codex_rmcp_client::perform_oauth_login_silent;
#[derive(Clone)]
@@ -1437,15 +1440,24 @@ impl PluginRequestProcessor {
}
let plugins_manager = self.thread_manager.plugins_manager();
let marketplace_display = marketplace_path.display().to_string();
let plugin_name_for_log = plugin_name.clone();
let request = PluginInstallRequest {
plugin_name,
marketplace_path,
};
let result = plugins_manager
.install_plugin(request)
.await
.map_err(Self::plugin_install_error)?;
let result = match plugins_manager.install_plugin(request).await {
Ok(result) => result,
Err(err) => {
warn!(
marketplace = %marketplace_display,
plugin_name = %plugin_name_for_log,
"failed to install plugin: {err}"
);
return Err(Self::plugin_install_error(err));
}
};
let config = match self.load_latest_config(config_cwd).await {
Ok(config) => config,
Err(err) => {
@@ -1512,11 +1524,20 @@ impl PluginRequestProcessor {
)
.await
.map_err(|err| {
let error_type = remote_plugin_catalog_error_type(&err);
self.track_plugin_install_failed_for_remote_plugin(
&remote_plugin_id,
&remote_marketplace_name,
error_type,
err.to_string(),
);
remote_plugin_catalog_error_to_jsonrpc(
err,
"read remote plugin details before install",
)
})?;
let actual_remote_marketplace_name = remote_detail.marketplace_name.clone();
let remote_plugin_name = remote_detail.summary.name.clone();
if remote_detail.summary.availability == PluginAvailability::DisabledByAdmin {
return Err(invalid_request(format!(
"remote plugin {remote_plugin_id} is disabled by admin"
@@ -1527,31 +1548,48 @@ impl PluginRequestProcessor {
"remote plugin {remote_plugin_id} is not available for install"
)));
}
let actual_remote_marketplace_name = remote_detail.marketplace_name.clone();
// Direct install writes the same cache tree that installed-plugin sync
// prunes before the backend installed snapshot can include this plugin.
let _remote_plugin_cache_mutation =
codex_core_plugins::remote::mark_remote_plugin_cache_mutation_in_flight(
config.codex_home.as_path(),
&actual_remote_marketplace_name,
&remote_detail.summary.name,
&remote_plugin_name,
);
let validated_bundle = codex_core_plugins::remote_bundle::validate_remote_plugin_bundle(
&remote_plugin_id,
&actual_remote_marketplace_name,
&remote_detail.summary.name,
&remote_plugin_name,
remote_detail.release_version.as_deref(),
remote_detail.bundle_download_url.as_deref(),
remote_detail.app_manifest.clone(),
)
.map_err(remote_plugin_bundle_install_error_to_jsonrpc)?;
.map_err(|err| {
let error_type = remote_plugin_bundle_install_error_type(&err);
self.track_plugin_install_failed_for_remote_plugin(
&remote_plugin_id,
&actual_remote_marketplace_name,
error_type,
err.to_string(),
);
remote_plugin_bundle_install_error_to_jsonrpc(err)
})?;
let result = codex_core_plugins::remote_bundle::download_and_install_remote_plugin_bundle(
config.codex_home.to_path_buf(),
validated_bundle,
)
.await
.map_err(remote_plugin_bundle_install_error_to_jsonrpc)?;
.map_err(|err| {
let error_type = remote_plugin_bundle_install_error_type(&err);
self.track_plugin_install_failed_for_remote_plugin(
&remote_plugin_id,
&actual_remote_marketplace_name,
error_type,
err.to_string(),
);
remote_plugin_bundle_install_error_to_jsonrpc(err)
})?;
// Cache first so a backend install cannot succeed when local materialization fails.
// If this backend call fails, the cache entry is harmless because remote installed state
@@ -1563,7 +1601,16 @@ impl PluginRequestProcessor {
&remote_plugin_id,
)
.await
.map_err(|err| remote_plugin_catalog_error_to_jsonrpc(err, "install remote plugin"))?;
.map_err(|err| {
let error_type = remote_plugin_catalog_error_type(&err);
self.track_plugin_install_failed_for_remote_plugin(
&remote_plugin_id,
&actual_remote_marketplace_name,
error_type,
err.to_string(),
);
remote_plugin_catalog_error_to_jsonrpc(err, "install remote plugin")
})?;
self.thread_manager
.plugins_manager()
@@ -1646,6 +1693,32 @@ impl PluginRequestProcessor {
})
}
fn track_plugin_install_failed_for_remote_plugin(
&self,
remote_plugin_id: &str,
marketplace_name: &str,
error_type: &'static str,
error_message: String,
) {
tracing::warn!(
remote_plugin_id = %remote_plugin_id,
marketplace_name = %marketplace_name,
error_type = %error_type,
error = %error_message,
"remote plugin install failed"
);
// The remote id is reported separately; this local name only satisfies
// PluginId validation before remote details are available.
let Ok(plugin_id) = PluginId::new("unknown".to_string(), marketplace_name.to_string())
else {
return;
};
let mut plugin = PluginTelemetryMetadata::from_plugin_id(&plugin_id);
plugin.remote_plugin_id = Some(remote_plugin_id.to_string());
self.analytics_events_client
.track_plugin_install_failed(plugin, error_type.to_string());
}
async fn plugin_apps_needing_auth_for_install(
&self,
config: &Config,
@@ -2145,6 +2218,75 @@ fn remote_plugin_detail_to_info(
}
}
fn remote_plugin_catalog_error_type(err: &RemotePluginCatalogError) -> &'static str {
match err {
RemotePluginCatalogError::AuthRequired => "remote_catalog_auth_required",
RemotePluginCatalogError::UnsupportedAuthMode => "remote_catalog_unsupported_auth_mode",
RemotePluginCatalogError::AuthToken(_) => "remote_catalog_auth_token",
RemotePluginCatalogError::Request { .. } => "remote_catalog_request",
RemotePluginCatalogError::UnexpectedStatus { .. } => "remote_catalog_unexpected_status",
RemotePluginCatalogError::Decode { .. } => "remote_catalog_decode",
RemotePluginCatalogError::InvalidBaseUrl(_) => "remote_catalog_invalid_base_url",
RemotePluginCatalogError::InvalidBaseUrlPath => "remote_catalog_invalid_base_url_path",
RemotePluginCatalogError::UnknownMarketplace { .. } => "remote_catalog_unknown_marketplace",
RemotePluginCatalogError::UnexpectedPluginId { .. } => {
"remote_catalog_unexpected_plugin_id"
}
RemotePluginCatalogError::UnexpectedSkillName { .. } => {
"remote_catalog_unexpected_skill_name"
}
RemotePluginCatalogError::UnexpectedEnabledState { .. } => {
"remote_catalog_unexpected_enabled_state"
}
RemotePluginCatalogError::InvalidPluginPath { .. } => "remote_catalog_invalid_plugin_path",
RemotePluginCatalogError::PluginShareCheckoutNotAvailable { .. } => {
"remote_catalog_plugin_share_checkout_not_available"
}
RemotePluginCatalogError::Archive { .. } => "remote_catalog_archive",
RemotePluginCatalogError::ArchiveJoin(_) => "remote_catalog_archive_join",
RemotePluginCatalogError::ArchiveTooLarge { .. } => "remote_catalog_archive_too_large",
RemotePluginCatalogError::MissingUploadEtag => "remote_catalog_missing_upload_etag",
RemotePluginCatalogError::UnexpectedResponse(_) => "remote_catalog_unexpected_response",
RemotePluginCatalogError::CacheRemove(_) => "remote_catalog_cache_remove",
}
}
fn remote_plugin_bundle_install_error_type(err: &RemotePluginBundleInstallError) -> &'static str {
match err {
RemotePluginBundleInstallError::MissingReleaseVersion { .. } => {
"remote_bundle_missing_release_version"
}
RemotePluginBundleInstallError::InvalidReleaseVersion { .. } => {
"remote_bundle_invalid_release_version"
}
RemotePluginBundleInstallError::MissingBundleDownloadUrl { .. } => {
"remote_bundle_missing_download_url"
}
RemotePluginBundleInstallError::InvalidBundleDownloadUrl { .. } => {
"remote_bundle_invalid_download_url"
}
RemotePluginBundleInstallError::UnsupportedBundleDownloadUrlScheme { .. } => {
"remote_bundle_unsupported_download_url_scheme"
}
RemotePluginBundleInstallError::InvalidPluginId { .. } => "remote_bundle_invalid_plugin_id",
RemotePluginBundleInstallError::DownloadRequest { .. } => "remote_bundle_download_request",
RemotePluginBundleInstallError::DownloadStatus { .. } => "remote_bundle_download_status",
RemotePluginBundleInstallError::DownloadBody { .. } => "remote_bundle_download_body",
RemotePluginBundleInstallError::DownloadTooLarge { .. } => {
"remote_bundle_download_too_large"
}
RemotePluginBundleInstallError::UnsupportedBundleDownloadFinalUrl { .. } => {
"remote_bundle_unsupported_download_final_url"
}
RemotePluginBundleInstallError::ExtractedBundleTooLarge { .. } => {
"remote_bundle_extracted_too_large"
}
RemotePluginBundleInstallError::Io { .. } => "remote_bundle_io",
RemotePluginBundleInstallError::InvalidBundle(_) => "remote_bundle_invalid_bundle",
RemotePluginBundleInstallError::Store(_) => "remote_bundle_store",
}
}
fn remote_plugin_catalog_error_to_jsonrpc(
err: RemotePluginCatalogError,
context: &str,
@@ -1781,16 +1781,22 @@ impl ThreadRequestProcessor {
.list_background_terminals()
.await
.into_iter()
.map(|terminal| ThreadBackgroundTerminal {
item_id: terminal.item_id,
process_id: terminal.process_id,
command: terminal.command,
cwd: terminal.cwd,
os_pid: None,
cpu_percent: None,
rss_kb: None,
.map(|terminal| {
// TODO(anp): Migrate ThreadBackgroundTerminal to PathUri.
let cwd = terminal.cwd.to_abs_path().map_err(|err| {
internal_error(format!("background terminal has invalid cwd: {err}"))
})?;
Ok(ThreadBackgroundTerminal {
item_id: terminal.item_id,
process_id: terminal.process_id,
command: terminal.command,
cwd,
os_pid: None,
cpu_percent: None,
rss_kb: None,
})
})
.collect::<Vec<_>>();
.collect::<Result<Vec<_>, JSONRPCErrorError>>()?;
let (data, next_cursor) = paginate_background_terminals(&terminals, cursor, limit)?;
@@ -1897,6 +1903,7 @@ impl ThreadRequestProcessor {
let store_sort_key = match sort_key.unwrap_or(ThreadSortKey::CreatedAt) {
ThreadSortKey::CreatedAt => StoreThreadSortKey::CreatedAt,
ThreadSortKey::UpdatedAt => StoreThreadSortKey::UpdatedAt,
ThreadSortKey::RecencyAt => StoreThreadSortKey::RecencyAt,
};
let sort_direction = sort_direction.unwrap_or(SortDirection::Desc);
let (stored_threads, next_cursor) = self
@@ -1978,6 +1985,7 @@ impl ThreadRequestProcessor {
let store_sort_key = match sort_key.unwrap_or(ThreadSortKey::CreatedAt) {
ThreadSortKey::CreatedAt => StoreThreadSortKey::CreatedAt,
ThreadSortKey::UpdatedAt => StoreThreadSortKey::UpdatedAt,
ThreadSortKey::RecencyAt => StoreThreadSortKey::RecencyAt,
};
let store_sort_direction = sort_direction.unwrap_or(SortDirection::Desc);
let (allowed_sources, source_kind_filter) = compute_source_filters(source_kinds);
@@ -3695,6 +3703,7 @@ fn thread_backwards_cursor_for_sort_key(
let timestamp = match sort_key {
StoreThreadSortKey::CreatedAt => thread.created_at,
StoreThreadSortKey::UpdatedAt => thread.updated_at,
StoreThreadSortKey::RecencyAt => thread.recency_at,
};
// The state DB stores unique millisecond timestamps. Offset the reverse cursor by one
// millisecond so the opposite-direction query includes the page anchor.
@@ -4139,6 +4148,7 @@ pub(crate) fn thread_from_stored_thread(
},
created_at: thread.created_at.timestamp(),
updated_at: thread.updated_at.timestamp(),
recency_at: Some(thread.recency_at.timestamp()),
status: ThreadStatus::NotLoaded,
path,
cwd,
@@ -4344,6 +4354,7 @@ fn build_thread_from_snapshot(
model_provider: config_snapshot.model_provider_id.clone(),
created_at: now,
updated_at: now,
recency_at: Some(now),
status: ThreadStatus::NotLoaded,
path,
cwd: config_snapshot.cwd().clone(),
@@ -478,6 +478,7 @@ mod thread_processor_behavior_tests {
reasoning_effort: None,
created_at: created_at.with_timezone(&Utc),
updated_at: updated_at.with_timezone(&Utc),
recency_at: updated_at.with_timezone(&Utc),
archived_at: None,
cwd: PathBuf::from("/tmp"),
cli_version: "0.0.0".to_string(),
@@ -178,6 +178,7 @@ mod tests {
model_provider: "mock_provider".to_string(),
created_at: 0,
updated_at: 0,
recency_at: Some(0),
status: ThreadStatus::Idle,
path: None,
cwd: test_path_buf("/tmp").abs(),
@@ -320,6 +320,7 @@ pub(crate) fn summary_to_thread(
model_provider,
created_at: created_at.map(|dt| dt.timestamp()).unwrap_or(0),
updated_at: updated_at.map(|dt| dt.timestamp()).unwrap_or(0),
recency_at: updated_at.map(|dt| dt.timestamp()),
status: ThreadStatus::NotLoaded,
path: (!path.as_os_str().is_empty()).then_some(path),
cwd,
@@ -931,8 +931,10 @@ impl TurnRequestProcessor {
thread.as_ref(),
Op::RealtimeConversationStart(ConversationStartParams {
architecture: params.architecture,
client_managed_handoffs: params.client_managed_handoffs.unwrap_or(false),
codex_responses_as_items: params.codex_responses_as_items.unwrap_or(false),
codex_response_item_prefix: params.codex_response_item_prefix,
codex_response_handoff_prefix: params.codex_response_handoff_prefix,
model: params.model,
output_modality: params.output_modality,
include_startup_context: params.include_startup_context.unwrap_or(true),
+1
View File
@@ -897,6 +897,7 @@ mod tests {
model_provider: "mock-provider".to_string(),
created_at: 0,
updated_at: 0,
recency_at: Some(0),
status: ThreadStatus::NotLoaded,
path: None,
cwd: test_path_buf("/tmp").abs(),
@@ -137,6 +137,7 @@ async fn auto_compaction_remote_emits_started_and_completed_items() -> Result<()
metadata: None,
},
ResponseItem::Compaction {
id: None,
encrypted_content: "ENCRYPTED_COMPACTION_SUMMARY".to_string(),
metadata: None,
},
@@ -80,8 +80,10 @@ async fn realtime_conversation_start_requires_experimental_api_capability() -> R
let request_id = mcp
.send_thread_realtime_start_request(ThreadRealtimeStartParams {
architecture: None,
client_managed_handoffs: None,
codex_responses_as_items: None,
codex_response_item_prefix: None,
codex_response_handoff_prefix: None,
thread_id: "thr_123".to_string(),
model: None,
output_modality: RealtimeOutputModality::Audio,
@@ -192,8 +194,10 @@ async fn realtime_webrtc_start_requires_experimental_api_capability() -> Result<
let request_id = mcp
.send_thread_realtime_start_request(ThreadRealtimeStartParams {
architecture: None,
client_managed_handoffs: None,
codex_responses_as_items: None,
codex_response_item_prefix: None,
codex_response_handoff_prefix: None,
thread_id: "thr_123".to_string(),
model: None,
output_modality: RealtimeOutputModality::Audio,
@@ -1,9 +1,12 @@
use std::time::Duration;
use anyhow::Result;
use app_test_support::ChatGptAuthFixture;
use app_test_support::TestAppServer;
use app_test_support::create_mock_responses_server_repeating_assistant;
use app_test_support::start_analytics_events_server;
use app_test_support::to_response;
use app_test_support::write_chatgpt_auth;
use app_test_support::write_mock_responses_config_toml;
use codex_app_server_protocol::ExternalAgentConfigDetectResponse;
use codex_app_server_protocol::ExternalAgentConfigImportCompletedNotification;
@@ -11,7 +14,6 @@ use codex_app_server_protocol::ExternalAgentConfigImportHistoriesReadResponse;
use codex_app_server_protocol::ExternalAgentConfigImportProgressNotification;
use codex_app_server_protocol::ExternalAgentConfigImportResponse;
use codex_app_server_protocol::ExternalAgentConfigMigrationItemType;
use codex_app_server_protocol::JSONRPCError;
use codex_app_server_protocol::JSONRPCResponse;
use codex_app_server_protocol::PluginListParams;
use codex_app_server_protocol::PluginListResponse;
@@ -25,16 +27,25 @@ use codex_app_server_protocol::ThreadResumeParams;
use codex_app_server_protocol::ThreadResumeResponse;
use codex_app_server_protocol::TurnStartParams;
use codex_app_server_protocol::UserInput;
use codex_config::types::AuthCredentialsStoreMode;
use core_test_support::responses;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
use std::path::Path;
use std::path::PathBuf;
use tempfile::TempDir;
#[cfg(unix)]
use tokio::io::AsyncWriteExt;
use tokio::time::timeout;
use super::analytics::wait_for_analytics_event;
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60);
fn external_agent_home(codex_home: &Path) -> PathBuf {
codex_home.join(concat!(".", "cl", "aude"))
}
fn assert_import_response(response: ExternalAgentConfigImportResponse) -> String {
assert!(!response.import_id.is_empty());
response.import_id
@@ -158,15 +169,172 @@ async fn external_agent_config_import_sends_completion_notification_for_sync_onl
}
#[tokio::test]
async fn external_agent_config_import_returns_error_for_failed_sync_import() -> Result<()> {
async fn external_agent_config_import_reports_failed_sync_import_in_completion() -> Result<()> {
let codex_home = TempDir::new()?;
std::fs::create_dir_all(codex_home.path().join(".claude"))?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("account-123")
.chatgpt_user_id("user-123")
.chatgpt_account_id("account-123"),
AuthCredentialsStoreMode::File,
)?;
let source_home = external_agent_home(codex_home.path());
std::fs::create_dir_all(&source_home)?;
std::fs::write(
codex_home.path().join(".claude").join("settings.json"),
source_home.join("settings.json"),
r#"{"env":{"FOO":"bar"}}"#,
)?;
std::fs::write(codex_home.path().join("config.toml"), "invalid = [")?;
let home_dir = codex_home.path().display().to_string();
let analytics_capture_file = codex_home.path().join("analytics-events.jsonl");
let analytics_capture_file = analytics_capture_file.display().to_string();
let mut mcp = TestAppServer::new_with_env(
codex_home.path(),
&[
("HOME", Some(home_dir.as_str())),
(
"CODEX_ANALYTICS_EVENTS_CAPTURE_FILE",
Some(analytics_capture_file.as_str()),
),
],
)
.await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
let request_id = mcp
.send_raw_request(
"externalAgentConfig/import",
Some(serde_json::json!({
"source": "test_import",
"migrationItems": [
{
"itemType": "CONFIG",
"description": "Import config",
"cwd": null
},
{
"itemType": "COMMANDS",
"description": "Import commands",
"cwd": null
}
]
})),
)
.await?;
let response: JSONRPCResponse = timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??;
let response: ExternalAgentConfigImportResponse = to_response(response)?;
let import_id = assert_import_response(response);
let notification = timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_notification_message("externalAgentConfig/import/completed"),
)
.await??;
let completed: ExternalAgentConfigImportCompletedNotification =
serde_json::from_value(notification.params.expect("completed params"))?;
assert_eq!(completed.import_id, import_id);
let config_result = completed
.item_type_results
.iter()
.find(|result| result.item_type == ExternalAgentConfigMigrationItemType::Config)
.expect("config result");
assert!(config_result.successes.is_empty());
assert_eq!(config_result.failures.len(), 1);
let config_failure = &config_result.failures[0];
assert_eq!(
config_failure.error_type.as_deref(),
Some("invalid_existing_config")
);
assert_eq!(config_failure.failure_stage, "import_request_failed");
assert!(
config_failure
.message
.contains("invalid existing config.toml"),
"unexpected failure: {config_failure:?}"
);
let commands_result = completed
.item_type_results
.iter()
.find(|result| result.item_type == ExternalAgentConfigMigrationItemType::Commands)
.expect("commands result");
assert!(commands_result.successes.is_empty());
assert!(commands_result.failures.is_empty());
let events = timeout(DEFAULT_TIMEOUT, async {
loop {
let contents = match std::fs::read_to_string(&analytics_capture_file) {
Ok(contents) => contents,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
tokio::time::sleep(Duration::from_millis(25)).await;
continue;
}
Err(err) => return Err(err.into()),
};
let mut captured_events = Vec::new();
for line in contents.lines() {
let payload: serde_json::Value = serde_json::from_str(line)?;
let Some(events) = payload["events"].as_array() else {
continue;
};
captured_events.extend(events.iter().cloned());
}
if captured_events.iter().any(|event| {
event["event_type"] == "codex_onboarding_external_agent_import_complete"
&& event["event_params"]["type"] == "COMMANDS"
}) {
return Ok::<Vec<serde_json::Value>, anyhow::Error>(captured_events);
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
})
.await??;
let event = events
.iter()
.find(|event| {
event["event_type"] == "codex_onboarding_external_agent_import_failure"
&& event["event_params"]["type"] == "CONFIG"
})
.expect("config failure analytics event");
let event_params = &event["event_params"];
assert_eq!(event_params["import_id"], import_id);
assert_eq!(event_params["source"], "test_import");
assert_eq!(event_params["type"], "CONFIG");
assert_eq!(event_params["failure_stage"], "import_request_failed");
assert_eq!(event_params["error_type"], "invalid_existing_config");
assert!(event_params.get("raw_errors").is_none());
assert!(event_params.get("message").is_none());
assert!(!events.iter().any(|event| {
event["event_type"] == "codex_onboarding_external_agent_import_failure"
&& event["event_params"]["type"] == "COMMANDS"
}));
Ok(())
}
#[tokio::test]
async fn external_agent_config_import_completed_tracks_analytics_event() -> Result<()> {
let analytics_server = start_analytics_events_server().await?;
let codex_home = TempDir::new()?;
write_analytics_config(codex_home.path(), &analytics_server.uri())?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("account-123")
.chatgpt_user_id("user-123")
.chatgpt_account_id("account-123"),
AuthCredentialsStoreMode::File,
)?;
let missing_session_path =
external_agent_home(codex_home.path()).join("projects/repo/missing.jsonl");
let project_root = codex_home.path().join("repo");
let home_dir = codex_home.path().display().to_string();
let mut mcp =
TestAppServer::new_with_env(codex_home.path(), &[("HOME", Some(home_dir.as_str()))])
.await?;
@@ -176,25 +344,70 @@ async fn external_agent_config_import_returns_error_for_failed_sync_import() ->
.send_raw_request(
"externalAgentConfig/import",
Some(serde_json::json!({
"source": "test_import",
"migrationItems": [{
"itemType": "CONFIG",
"description": "Import config",
"cwd": null
"itemType": "SESSIONS",
"description": "Migrate recent sessions",
"cwd": null,
"details": {
"sessions": [{
"path": missing_session_path,
"cwd": project_root,
"title": "missing session"
}]
}
}]
})),
)
.await?;
let error: JSONRPCError = timeout(
let response: JSONRPCResponse = timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_error_message(RequestId::Integer(request_id)),
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??;
assert_eq!(error.error.code, -32603);
assert!(
error.error.message.contains("invalid existing config.toml"),
"unexpected error: {error:?}"
);
let response: ExternalAgentConfigImportResponse = to_response(response)?;
let import_id = assert_import_response(response);
let notification = timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_notification_message("externalAgentConfig/import/completed"),
)
.await??;
let completed: ExternalAgentConfigImportCompletedNotification =
serde_json::from_value(notification.params.expect("completed params"))?;
assert_eq!(completed.import_id, import_id);
assert_eq!(completed.item_type_results.len(), 1);
assert_eq!(completed.item_type_results[0].successes.len(), 0);
assert_eq!(completed.item_type_results[0].failures.len(), 1);
let event = wait_for_analytics_event(
&analytics_server,
DEFAULT_TIMEOUT,
"codex_onboarding_external_agent_import_complete",
)
.await?;
let event_params = &event["event_params"];
assert_eq!(event_params["import_id"], serde_json::json!(import_id));
assert_eq!(event_params["source"], "test_import");
assert_eq!(event_params["type"], "SESSIONS");
assert_eq!(event_params["success_count"], 0);
assert_eq!(event_params["failed_count"], 1);
assert!(event_params.get("raw_errors").is_none());
let event = wait_for_analytics_event(
&analytics_server,
DEFAULT_TIMEOUT,
"codex_onboarding_external_agent_import_failure",
)
.await?;
let event_params = &event["event_params"];
assert_eq!(event_params["import_id"], serde_json::json!(import_id));
assert_eq!(event_params["source"], "test_import");
assert_eq!(event_params["type"], "SESSIONS");
assert_eq!(event_params["failure_stage"], "session_missing");
assert_eq!(event_params["error_type"], "session_missing");
assert!(event_params.get("raw_errors").is_none());
assert!(event_params.get("message").is_none());
Ok(())
}
@@ -226,7 +439,8 @@ async fn external_agent_config_import_sends_completion_notification_for_local_pl
plugin_root.join(".codex-plugin/plugin.json"),
r#"{"name":"sample","version":"0.1.0"}"#,
)?;
std::fs::create_dir_all(codex_home.path().join(".claude"))?;
let source_home = external_agent_home(codex_home.path());
std::fs::create_dir_all(&source_home)?;
let settings = serde_json::json!({
"enabledPlugins": {
"sample@debug": true
@@ -239,7 +453,7 @@ async fn external_agent_config_import_sends_completion_notification_for_local_pl
}
});
std::fs::write(
codex_home.path().join(".claude").join("settings.json"),
source_home.join("settings.json"),
serde_json::to_string_pretty(&settings)?,
)?;
@@ -318,11 +532,12 @@ async fn external_agent_config_import_sends_completion_notification_for_local_pl
async fn external_agent_config_import_sends_completion_notification_after_pending_plugins_finish()
-> Result<()> {
let codex_home = TempDir::new()?;
std::fs::create_dir_all(codex_home.path().join(".claude"))?;
let source_home = external_agent_home(codex_home.path());
std::fs::create_dir_all(&source_home)?;
// This test only needs a pending non-local plugin import. Use an invalid
// source so the background completion path cannot make a real network clone.
std::fs::write(
codex_home.path().join(".claude").join("settings.json"),
source_home.join("settings.json"),
r#"{
"enabledPlugins": {
"formatter@acme-tools": true
@@ -387,7 +602,7 @@ async fn external_agent_config_import_creates_session_rollouts() -> Result<()> {
create_config_toml(codex_home.path(), &server.uri())?;
let project_root = codex_home.path().join("repo");
let recent_timestamp = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
let session_dir = codex_home.path().join(".claude/projects/repo");
let session_dir = external_agent_home(codex_home.path()).join("projects/repo");
let session_path = session_dir.join("session.jsonl");
std::fs::create_dir_all(&project_root)?;
std::fs::create_dir_all(&session_dir)?;
@@ -613,7 +828,7 @@ required = true
std::fs::write(codex_home.path().join("config.toml"), config)?;
let project_root = codex_home.path().join("repo");
let recent_timestamp = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
let session_dir = codex_home.path().join(".claude/projects/repo");
let session_dir = external_agent_home(codex_home.path()).join("projects/repo");
let session_path = session_dir.join("session.jsonl");
std::fs::create_dir_all(&project_root)?;
std::fs::create_dir_all(&session_dir)?;
@@ -698,7 +913,7 @@ async fn external_agent_config_import_accepts_detected_session_payload_after_res
create_config_toml(codex_home.path(), &server.uri())?;
let project_root = codex_home.path().join("repo");
let recent_timestamp = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
let session_dir = codex_home.path().join(".claude/projects/repo");
let session_dir = external_agent_home(codex_home.path()).join("projects/repo");
let session_path = session_dir.join("session.jsonl");
std::fs::create_dir_all(&project_root)?;
std::fs::create_dir_all(&session_dir)?;
@@ -788,7 +1003,7 @@ async fn external_agent_config_import_skips_already_imported_session_versions()
create_config_toml(codex_home.path(), &server.uri())?;
let project_root = codex_home.path().join("repo");
let recent_timestamp = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
let session_dir = codex_home.path().join(".claude/projects/repo");
let session_dir = external_agent_home(codex_home.path()).join("projects/repo");
let session_path = session_dir.join("session.jsonl");
std::fs::create_dir_all(&project_root)?;
std::fs::create_dir_all(&session_dir)?;
@@ -882,7 +1097,7 @@ async fn external_agent_config_import_returns_before_background_session_import_f
create_config_toml(codex_home.path(), &server.uri())?;
let project_root = codex_home.path().join("repo");
let recent_timestamp = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
let session_dir = codex_home.path().join(".claude/projects/repo");
let session_dir = external_agent_home(codex_home.path()).join("projects/repo");
let session_path = session_dir.join("session.jsonl");
std::fs::create_dir_all(&project_root)?;
std::fs::create_dir_all(&session_dir)?;
@@ -1043,7 +1258,7 @@ async fn external_agent_config_import_compacts_huge_session_before_first_follow_
let project_root = codex_home.path().join("repo");
let recent_timestamp = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
let session_dir = codex_home.path().join(".claude/projects/repo");
let session_dir = external_agent_home(codex_home.path()).join("projects/repo");
let session_path = session_dir.join("session.jsonl");
std::fs::create_dir_all(&project_root)?;
std::fs::create_dir_all(&session_dir)?;
@@ -1209,3 +1424,10 @@ stream_max_retries = 0
),
)
}
fn write_analytics_config(codex_home: &std::path::Path, base_url: &str) -> std::io::Result<()> {
std::fs::write(
codex_home.join("config.toml"),
format!("chatgpt_base_url = \"{base_url}\"\n"),
)
}
@@ -511,6 +511,46 @@ async fn plugin_install_rejects_invalid_remote_plugin_name() -> Result<()> {
Ok(())
}
#[tokio::test]
async fn plugin_install_tracks_analytics_when_remote_detail_fetch_fails() -> Result<()> {
let codex_home = TempDir::new()?;
let server = MockServer::start().await;
configure_remote_plugin_test(codex_home.path(), &server)?;
mount_empty_remote_installed_plugins(&server).await;
mount_backend_analytics_events(&server).await;
let mut mcp = TestAppServer::new(codex_home.path()).await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
let request_id = send_remote_plugin_install_request(&mut mcp, REMOTE_PLUGIN_ID).await?;
let err = timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_error_message(RequestId::Integer(request_id)),
)
.await??;
assert_eq!(err.error.code, -32600);
assert!(err.error.message.contains("failed with status 404"));
let payload = wait_for_plugin_analytics_payload(&server).await?;
let event_params = &payload["events"][0]["event_params"];
assert_eq!(
payload["events"][0]["event_type"],
"codex_plugin_install_failed"
);
assert_eq!(event_params["plugin_id"], REMOTE_PLUGIN_ID);
assert_eq!(event_params["plugin_name"], "unknown");
assert_eq!(
event_params["marketplace_name"],
"caller-marketplace-is-ignored"
);
assert_eq!(
event_params["error_type"],
"remote_catalog_unexpected_status"
);
Ok(())
}
#[tokio::test]
async fn plugin_install_rejects_remote_plugin_disabled_by_admin_before_download() -> Result<()> {
let codex_home = TempDir::new()?;
@@ -571,6 +611,42 @@ async fn plugin_install_rejects_remote_plugin_disabled_by_admin_before_download(
Ok(())
}
#[tokio::test]
async fn plugin_install_rejects_remote_plugin_not_available() -> Result<()> {
let codex_home = TempDir::new()?;
let server = MockServer::start().await;
configure_remote_plugin_test(codex_home.path(), &server)?;
mount_remote_plugin_detail_with_install_policy(
&server,
REMOTE_PLUGIN_ID,
"1.2.3",
/*install_policy*/ "NOT_AVAILABLE",
)
.await;
mount_empty_remote_installed_plugins(&server).await;
let mut mcp = TestAppServer::new(codex_home.path()).await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
let request_id = send_remote_plugin_install_request(&mut mcp, REMOTE_PLUGIN_ID).await?;
let err = timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_error_message(RequestId::Integer(request_id)),
)
.await??;
assert_eq!(err.error.code, -32600);
assert!(err.error.message.contains("not available for install"));
wait_for_remote_plugin_request_count(
&server,
"POST",
&format!("/ps/plugins/{REMOTE_PLUGIN_ID}/install"),
/*expected_count*/ 0,
)
.await?;
Ok(())
}
#[tokio::test]
async fn plugin_install_rejects_when_workspace_codex_plugins_disabled() -> Result<()> {
let codex_home = TempDir::new()?;
@@ -820,6 +896,66 @@ async fn plugin_install_tracks_analytics_event() -> Result<()> {
Ok(())
}
#[tokio::test]
async fn plugin_install_failure_tracks_analytics_event() -> Result<()> {
let analytics_server = start_analytics_events_server().await?;
let codex_home = TempDir::new()?;
write_analytics_config(codex_home.path(), &analytics_server.uri())?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("account-123")
.chatgpt_user_id("user-123")
.chatgpt_account_id("account-123"),
AuthCredentialsStoreMode::File,
)?;
let repo_root = TempDir::new()?;
write_plugin_marketplace(
repo_root.path(),
"debug",
"sample-plugin",
"./missing-plugin",
/*install_policy*/ None,
/*auth_policy*/ None,
)?;
let marketplace_path =
AbsolutePathBuf::try_from(repo_root.path().join(".agents/plugins/marketplace.json"))?;
let mut mcp = TestAppServer::new(codex_home.path()).await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
let request_id = mcp
.send_plugin_install_request(PluginInstallParams {
marketplace_path: Some(marketplace_path),
remote_marketplace_name: None,
plugin_name: "sample-plugin".to_string(),
})
.await?;
let err = timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_error_message(RequestId::Integer(request_id)),
)
.await??;
assert_eq!(err.error.code, -32600);
let payload = wait_for_plugin_analytics_payload(&analytics_server).await?;
let event_params = &payload["events"][0]["event_params"];
assert_eq!(
payload["events"][0]["event_type"],
"codex_plugin_install_failed"
);
assert_eq!(event_params["plugin_id"], "sample-plugin@debug");
assert_eq!(event_params["plugin_name"], "sample-plugin");
assert_eq!(event_params["marketplace_name"], "debug");
assert_eq!(event_params["has_skills"], json!(null));
assert_eq!(event_params["mcp_server_count"], json!(null));
assert_eq!(event_params["connector_ids"], json!(null));
assert_eq!(event_params["product_client_id"], DEFAULT_CLIENT_NAME);
assert_eq!(event_params["error_type"], "store_invalid");
Ok(())
}
#[tokio::test]
async fn plugin_install_tracks_remote_plugin_analytics_event() -> Result<()> {
let codex_home = TempDir::new()?;
@@ -887,6 +1023,7 @@ async fn plugin_install_errors_when_remote_bundle_download_fails() -> Result<()>
mount_remote_plugin_detail(&server, REMOTE_PLUGIN_ID, "1.2.3", Some(&bundle_url)).await;
mount_empty_remote_installed_plugins(&server).await;
mount_remote_plugin_install(&server, REMOTE_PLUGIN_ID).await;
mount_backend_analytics_events(&server).await;
let mut mcp = TestAppServer::new_with_env(
codex_home.path(),
@@ -918,6 +1055,15 @@ async fn plugin_install_errors_when_remote_bundle_download_fails() -> Result<()>
/*expected_count*/ 0,
)
.await?;
let payload = wait_for_plugin_analytics_payload(&server).await?;
let event_params = &payload["events"][0]["event_params"];
assert_eq!(
payload["events"][0]["event_type"],
"codex_plugin_install_failed"
);
assert_eq!(event_params["plugin_id"], REMOTE_PLUGIN_ID);
assert_eq!(event_params["marketplace_name"], "openai-curated-remote");
assert_eq!(event_params["error_type"], "remote_bundle_download_status");
assert!(
!codex_home
.path()
@@ -1867,6 +2013,45 @@ async fn mount_remote_plugin_detail_with_status_and_app_manifest(
bundle_download_url: Option<&str>,
status: PluginAvailability,
app_manifest: Option<serde_json::Value>,
) {
mount_remote_plugin_detail_with_options(
server,
remote_plugin_id,
release_version,
bundle_download_url,
status,
"AVAILABLE",
app_manifest,
)
.await;
}
async fn mount_remote_plugin_detail_with_install_policy(
server: &MockServer,
remote_plugin_id: &str,
release_version: &str,
install_policy: &str,
) {
mount_remote_plugin_detail_with_options(
server,
remote_plugin_id,
release_version,
/*bundle_download_url*/ None,
PluginAvailability::Available,
install_policy,
/*app_manifest*/ None,
)
.await;
}
async fn mount_remote_plugin_detail_with_options(
server: &MockServer,
remote_plugin_id: &str,
release_version: &str,
bundle_download_url: Option<&str>,
status: PluginAvailability,
install_policy: &str,
app_manifest: Option<serde_json::Value>,
) {
let status = match status {
PluginAvailability::Available => "ENABLED",
@@ -1883,7 +2068,7 @@ async fn mount_remote_plugin_detail_with_status_and_app_manifest(
"id": "{remote_plugin_id}",
"name": "linear",
"scope": "GLOBAL",
"installation_policy": "AVAILABLE",
"installation_policy": "{install_policy}",
"authentication_policy": "ON_USE",
"status": "{status}",
"release": {{
@@ -86,6 +86,8 @@ const V2_HANDOFF_COMPLETE_ACKNOWLEDGEMENT: &str =
"Background agent finished. Use the preceding [BACKEND] messages as the result.";
const RESPONSE_ITEM_PREFIX: &str =
"Use the following context to inform future responses, but do not speak it to the user.";
const RESPONSE_HANDOFF_PREFIX: &str =
"Silent Codex context. Do not speak, acknowledge, or summarize this item.";
#[derive(Debug, Clone, Copy)]
enum StartupContextConfig<'a> {
@@ -313,8 +315,9 @@ impl RealtimeE2eHarness {
}
async fn start_webrtc_realtime(&mut self, offer_sdp: &str) -> Result<StartedWebrtcRealtime> {
self.start_webrtc_realtime_with_codex_responses_as_items(
offer_sdp, /*codex_responses_as_items*/ None,
self.start_webrtc_realtime_with_codex_response_routing(
offer_sdp, /*client_managed_handoffs*/ None,
/*codex_responses_as_items*/ None, /*codex_response_handoff_prefix*/ None,
)
.await
}
@@ -323,17 +326,21 @@ impl RealtimeE2eHarness {
&mut self,
offer_sdp: &str,
) -> Result<StartedWebrtcRealtime> {
self.start_webrtc_realtime_with_codex_responses_as_items(
self.start_webrtc_realtime_with_codex_response_routing(
offer_sdp,
/*client_managed_handoffs*/ None,
/*codex_responses_as_items*/ Some(true),
/*codex_response_handoff_prefix*/ None,
)
.await
}
async fn start_webrtc_realtime_with_codex_responses_as_items(
async fn start_webrtc_realtime_with_codex_response_routing(
&mut self,
offer_sdp: &str,
client_managed_handoffs: Option<bool>,
codex_responses_as_items: Option<bool>,
codex_response_handoff_prefix: Option<&str>,
) -> Result<StartedWebrtcRealtime> {
// Starts realtime through the public JSON-RPC method, then waits for the same client-visible
// notifications a desktop app needs: started first, SDP answer second.
@@ -341,10 +348,12 @@ impl RealtimeE2eHarness {
.mcp
.send_thread_realtime_start_request(ThreadRealtimeStartParams {
architecture: None,
client_managed_handoffs,
thread_id: self.thread_id.clone(),
codex_response_item_prefix: codex_responses_as_items
.unwrap_or(false)
.then(|| RESPONSE_ITEM_PREFIX.to_string()),
codex_response_handoff_prefix: codex_response_handoff_prefix.map(str::to_string),
codex_responses_as_items,
model: None,
output_modality: RealtimeOutputModality::Audio,
@@ -611,8 +620,10 @@ async fn realtime_conversation_streams_v2_notifications() -> Result<()> {
let start_request_id = mcp
.send_thread_realtime_start_request(ThreadRealtimeStartParams {
architecture: None,
client_managed_handoffs: None,
codex_responses_as_items: None,
codex_response_item_prefix: None,
codex_response_handoff_prefix: None,
thread_id: thread_start.thread.id.clone(),
model: Some("realtime-treatment-model".to_string()),
output_modality: RealtimeOutputModality::Audio,
@@ -867,8 +878,10 @@ async fn realtime_start_can_skip_startup_context() -> Result<()> {
let start_request_id = mcp
.send_thread_realtime_start_request(ThreadRealtimeStartParams {
architecture: None,
client_managed_handoffs: None,
codex_responses_as_items: None,
codex_response_item_prefix: None,
codex_response_handoff_prefix: None,
thread_id: thread_start.thread.id.clone(),
model: None,
output_modality: RealtimeOutputModality::Audio,
@@ -964,8 +977,10 @@ async fn realtime_text_output_modality_requests_text_output_and_final_transcript
let start_request_id = mcp
.send_thread_realtime_start_request(ThreadRealtimeStartParams {
architecture: None,
client_managed_handoffs: None,
codex_responses_as_items: None,
codex_response_item_prefix: None,
codex_response_handoff_prefix: None,
thread_id: thread_start.thread.id.clone(),
model: None,
output_modality: RealtimeOutputModality::Text,
@@ -1144,8 +1159,10 @@ async fn realtime_conversation_stop_emits_closed_notification() -> Result<()> {
let start_request_id = mcp
.send_thread_realtime_start_request(ThreadRealtimeStartParams {
architecture: None,
client_managed_handoffs: None,
codex_responses_as_items: None,
codex_response_item_prefix: None,
codex_response_handoff_prefix: None,
thread_id: thread_start.thread.id.clone(),
model: None,
output_modality: RealtimeOutputModality::Audio,
@@ -1247,8 +1264,10 @@ async fn realtime_webrtc_start_emits_sdp_notification() -> Result<()> {
let start_request_id = mcp
.send_thread_realtime_start_request(ThreadRealtimeStartParams {
architecture: None,
client_managed_handoffs: None,
codex_responses_as_items: None,
codex_response_item_prefix: None,
codex_response_handoff_prefix: None,
thread_id: thread_id.clone(),
model: None,
output_modality: RealtimeOutputModality::Audio,
@@ -1480,6 +1499,135 @@ async fn webrtc_v1_default_automatic_output_uses_handoff_append() -> Result<()>
Ok(())
}
#[tokio::test]
async fn webrtc_v1_client_managed_handoffs_disable_automatic_output() -> Result<()> {
skip_if_no_network!(Ok(()));
let mut harness = RealtimeE2eHarness::new(
RealtimeTestVersion::V1,
main_loop_responses(vec![create_final_assistant_message_sse_response(
"client-managed output",
)?]),
realtime_sideband(vec![realtime_sideband_connection(vec![
vec![session_updated("sess_v1_client_managed_handoffs")],
vec![],
])]),
)
.await?;
let started = harness
.start_webrtc_realtime_with_codex_response_routing(
"v=offer\r\n",
/*client_managed_handoffs*/ Some(true),
/*codex_responses_as_items*/ None,
/*codex_response_handoff_prefix*/ None,
)
.await?;
assert_eq!(started.started.version, RealtimeConversationVersion::V1);
assert_v1_session_update(&harness.sideband_outbound_request(/*request_index*/ 0).await)?;
let turn_request_id = harness
.mcp
.send_turn_start_request(TurnStartParams {
thread_id: harness.thread_id.clone(),
input: vec![V2UserInput::Text {
text: "leave realtime delivery to the client".to_string(),
text_elements: Vec::new(),
}],
..Default::default()
})
.await?;
let turn_response: JSONRPCResponse = timeout(
DEFAULT_TIMEOUT,
harness
.mcp
.read_stream_until_response_message(RequestId::Integer(turn_request_id)),
)
.await??;
let _: TurnStartResponse = to_response(turn_response)?;
let _ = harness
.read_notification::<TurnCompletedNotification>("turn/completed")
.await?;
let automatic_handoff = timeout(
Duration::from_millis(200),
harness
.realtime_server
.wait_for_request(/*connection_index*/ 0, /*request_index*/ 1),
)
.await;
assert!(
automatic_handoff.is_err(),
"automatic Codex output should not reach realtime in client-managed handoff mode"
);
harness
.append_speech(harness.thread_id.clone(), "client-selected speech")
.await?;
assert_eq!(
harness.sideband_outbound_request(/*request_index*/ 1).await,
json!({
"type": "conversation.handoff.append",
"handoff_id": "codex",
"output_text": "client-selected speech",
})
);
harness.shutdown().await;
Ok(())
}
#[tokio::test]
async fn webrtc_v1_final_automatic_handoff_omits_silent_prefix() -> Result<()> {
skip_if_no_network!(Ok(()));
let mut harness = RealtimeE2eHarness::new(
RealtimeTestVersion::V1,
main_loop_responses(vec![create_final_assistant_message_sse_response(
"background progress",
)?]),
realtime_sideband(vec![realtime_sideband_connection(vec![
vec![
session_updated("sess_v1_prefixed_handoff"),
json!({
"type": "conversation.handoff.requested",
"handoff_id": "handoff_prefixed",
"item_id": "item_prefixed",
"input_transcript": "run the background task"
}),
],
vec![],
vec![],
])]),
)
.await?;
let started = harness
.start_webrtc_realtime_with_codex_response_routing(
"v=offer\r\n",
/*client_managed_handoffs*/ None,
/*codex_responses_as_items*/ None,
Some(RESPONSE_HANDOFF_PREFIX),
)
.await?;
assert_eq!(started.started.version, RealtimeConversationVersion::V1);
let _ = harness
.read_notification::<TurnCompletedNotification>("turn/completed")
.await?;
assert_eq!(
harness.sideband_outbound_request(/*request_index*/ 1).await,
json!({
"type": "conversation.handoff.append",
"handoff_id": "handoff_prefixed",
"output_text": "background progress",
})
);
harness.shutdown().await;
Ok(())
}
#[tokio::test]
async fn webrtc_v1_handoff_request_delegates_context_and_manual_append_speaks() -> Result<()> {
skip_if_no_network!(Ok(()));
@@ -2468,8 +2616,10 @@ async fn realtime_webrtc_start_surfaces_backend_error() -> Result<()> {
let start_request_id = mcp
.send_thread_realtime_start_request(ThreadRealtimeStartParams {
architecture: None,
client_managed_handoffs: None,
codex_responses_as_items: None,
codex_response_item_prefix: None,
codex_response_handoff_prefix: None,
thread_id: thread_start.thread.id,
model: None,
output_modality: RealtimeOutputModality::Audio,
@@ -2533,8 +2683,10 @@ async fn realtime_conversation_requires_feature_flag() -> Result<()> {
let start_request_id = mcp
.send_thread_realtime_start_request(ThreadRealtimeStartParams {
architecture: None,
client_managed_handoffs: None,
codex_responses_as_items: None,
codex_response_item_prefix: None,
codex_response_handoff_prefix: None,
thread_id: thread_start.thread.id.clone(),
model: None,
output_modality: RealtimeOutputModality::Audio,
@@ -1689,6 +1689,89 @@ async fn thread_list_sort_updated_at_orders_by_mtime() -> Result<()> {
Ok(())
}
#[tokio::test]
async fn thread_list_sort_recency_at_uses_state_db_order_with_provider_filter() -> Result<()> {
let codex_home = TempDir::new()?;
create_minimal_config(codex_home.path())?;
let id_old = create_fake_rollout(
codex_home.path(),
"2025-01-01T10-00-00",
"2025-01-01T10:00:00Z",
"Hello",
Some("mock_provider"),
/*git_info*/ None,
)?;
let id_new = create_fake_rollout(
codex_home.path(),
"2025-01-01T11-00-00",
"2025-01-01T11:00:00Z",
"Hello",
Some("mock_provider"),
/*git_info*/ None,
)?;
set_rollout_mtime(
rollout_path(codex_home.path(), "2025-01-01T10-00-00", &id_old).as_path(),
"2025-01-03T00:00:00Z",
)?;
let state_db =
codex_state::StateRuntime::init(codex_home.path().to_path_buf(), "mock_provider".into())
.await?;
state_db
.mark_backfill_complete(/*last_watermark*/ None)
.await?;
let rollout_config = codex_rollout::RolloutConfig {
codex_home: codex_home.path().to_path_buf(),
sqlite_home: codex_home.path().to_path_buf(),
cwd: codex_home.path().to_path_buf(),
model_provider_id: "mock_provider".to_string(),
generate_memories: false,
};
codex_core::RolloutRecorder::list_threads(
Some(state_db.clone()),
&rollout_config,
/*page_size*/ 10,
/*cursor*/ None,
codex_core::ThreadSortKey::CreatedAt,
codex_core::SortDirection::Desc,
codex_core::INTERACTIVE_SESSION_SOURCES.as_slice(),
/*model_providers*/ None,
/*cwd_filters*/ None,
"mock_provider",
/*search_term*/ None,
)
.await?;
state_db
.touch_thread_recency_at(
ThreadId::from_string(&id_new)?,
DateTime::<Utc>::from_timestamp(1_800_000_000, 0).expect("timestamp"),
)
.await?;
let mut mcp = init_mcp(codex_home.path()).await?;
let ThreadListResponse { data, .. } = list_threads_with_sort(
&mut mcp,
/*cursor*/ None,
Some(10),
Some(vec!["mock_provider".to_string()]),
/*source_kinds*/ None,
Some(ThreadSortKey::RecencyAt),
/*archived*/ None,
)
.await?;
assert_eq!(
data.iter()
.map(|thread| thread.id.as_str())
.collect::<Vec<_>>(),
vec![id_new.as_str(), id_old.as_str()]
);
assert!(data.iter().all(|thread| thread.recency_at.is_some()));
Ok(())
}
#[tokio::test]
async fn thread_list_updated_at_paginates_with_cursor() -> Result<()> {
let codex_home = TempDir::new()?;
@@ -2200,6 +2200,7 @@ async fn thread_resume_defers_updated_at_until_turn_start() -> Result<()> {
let ThreadResumeResponse { thread, .. } = to_response::<ThreadResumeResponse>(resume_resp)?;
assert_eq!(thread.updated_at, before_resume.updated_at);
assert_eq!(thread.recency_at, before_resume.recency_at);
assert_eq!(thread.status, ThreadStatus::Idle);
let after_modified = std::fs::metadata(&rollout.rollout_file_path)?.modified()?;
@@ -2234,7 +2235,7 @@ async fn thread_resume_defers_updated_at_until_turn_start() -> Result<()> {
let turn_id = mcp
.send_turn_start_request(TurnStartParams {
thread_id,
thread_id: thread_id.clone(),
input: vec![UserInput::Text {
text: "Hello".to_string(),
text_elements: Vec::new(),
@@ -2247,6 +2248,29 @@ async fn thread_resume_defers_updated_at_until_turn_start() -> Result<()> {
mcp.read_stream_until_response_message(RequestId::Integer(turn_id)),
)
.await??;
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("turn/started"),
)
.await??;
let read_id = mcp
.send_thread_read_request(ThreadReadParams {
thread_id: thread_id.clone(),
include_turns: false,
})
.await?;
let read_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(read_id)),
)
.await??;
let ThreadReadResponse {
thread: after_turn_start,
..
} = to_response::<ThreadReadResponse>(read_resp)?;
assert!(after_turn_start.recency_at > before_resume.recency_at);
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("turn/completed"),
+8 -3
View File
@@ -230,7 +230,7 @@ pub async fn verify_apply_patch_args(
MaybeApplyPatchVerified::Body(ApplyPatchAction {
changes,
patch,
cwd: effective_cwd,
cwd: effective_cwd.into(),
})
}
@@ -811,7 +811,9 @@ PATCH"#,
},
)]),
patch: argv[1].clone(),
cwd: AbsolutePathBuf::from_absolute_path(session_dir.path()).unwrap(),
cwd: AbsolutePathBuf::from_absolute_path(session_dir.path())
.unwrap()
.into(),
})
);
}
@@ -851,7 +853,10 @@ PATCH"#,
other => panic!("expected verified body, got {other:?}"),
};
assert_eq!(action.cwd.as_path(), worktree_dir.as_path());
assert_eq!(
action.cwd.to_abs_path().unwrap().as_path(),
worktree_dir.as_path()
);
let source_path = worktree_dir.join(source_name);
let change = action
+2 -2
View File
@@ -142,7 +142,7 @@ pub struct ApplyPatchAction {
pub patch: String,
/// The working directory that was used to resolve relative paths in the patch.
pub cwd: AbsolutePathBuf,
pub cwd: PathUri,
}
impl ApplyPatchAction {
@@ -174,7 +174,7 @@ impl ApplyPatchAction {
#[expect(clippy::expect_used)]
Self {
changes,
cwd: path.parent().expect("path should have parent"),
cwd: path.parent().expect("path should have parent").into(),
patch,
}
}
+1 -1
View File
@@ -17,7 +17,7 @@ pub(crate) fn attach_item_ids(payload_json: &mut Value, original_items: &[Respon
};
for (value, item) in items.iter_mut().zip(original_items.iter()) {
if let ResponseItem::Reasoning { id, .. }
if let ResponseItem::Reasoning { id: Some(id), .. }
| ResponseItem::Message { id: Some(id), .. }
| ResponseItem::WebSearchCall { id: Some(id), .. }
| ResponseItem::FunctionCall { id: Some(id), .. }
+6
View File
@@ -48,6 +48,12 @@ pub use codex_core::resolve_installation_id;
pub use codex_core::skills::SkillsService;
pub use codex_core::thread_store_from_config;
pub use codex_exec_server::EnvironmentManager;
pub use codex_exec_server::EnvironmentRegistryConnectRequest;
pub use codex_exec_server::EnvironmentRegistryConnectResponse;
pub use codex_exec_server::EnvironmentRegistryHarnessKeyValidationRequest;
pub use codex_exec_server::EnvironmentRegistryHarnessKeyValidationResponse;
pub use codex_exec_server::EnvironmentRegistryRegistrationRequest;
pub use codex_exec_server::EnvironmentRegistryRegistrationResponse;
pub use codex_exec_server::ExecServerError;
pub use codex_exec_server::ExecServerRuntimePaths;
pub use codex_exec_server::NoiseChannelIdentity;
+163 -8
View File
@@ -69,6 +69,7 @@ use codex_plugin::AppConnectorId;
use codex_plugin::PluginCapabilitySummary;
use codex_plugin::PluginId;
use codex_plugin::PluginIdError;
use codex_plugin::PluginTelemetryMetadata;
use codex_plugin::app_connector_ids_from_declarations;
use codex_plugin::prompt_safe_plugin_description;
use codex_protocol::protocol::HookEventName;
@@ -941,6 +942,14 @@ impl PluginsManager {
Ok(featured_plugin_ids)
}
#[instrument(
level = "trace",
skip_all,
fields(
plugins_enabled = config.plugins_enabled,
remote_plugin_enabled = config.remote_plugin_enabled
)
)]
pub async fn recommended_plugins_mode_for_config(
&self,
config: &PluginsConfigInput,
@@ -1013,6 +1022,7 @@ impl PluginsManager {
/// Returns endpoint recommendations eligible for installation in the current client.
/// `None` selects the legacy discovery workflow.
#[instrument(level = "trace", skip_all)]
pub async fn recommended_plugin_candidates_for_config(
&self,
input: RecommendedPluginCandidatesInput<'_>,
@@ -1079,12 +1089,29 @@ impl PluginsManager {
&self,
request: PluginInstallRequest,
) -> Result<PluginInstallOutcome, PluginInstallError> {
let resolved = find_installable_marketplace_plugin(
let resolved = match find_installable_marketplace_plugin(
&request.marketplace_path,
&request.plugin_name,
self.restriction_product,
)?;
self.install_resolved_plugin(resolved).await
) {
Ok(resolved) => resolved,
Err(err) => {
self.track_plugin_install_resolution_failed(&err);
return Err(err.into());
}
};
let plugin_id = resolved.plugin_id.clone();
match self.install_resolved_plugin(resolved).await {
Ok(outcome) => Ok(outcome),
Err(err) => {
self.track_plugin_install_failed(
&plugin_id,
plugin_install_error_type(&err),
err.to_string(),
);
Err(err)
}
}
}
pub async fn install_plugin_with_remote_sync(
@@ -1093,21 +1120,101 @@ impl PluginsManager {
auth: Option<&CodexAuth>,
request: PluginInstallRequest,
) -> Result<PluginInstallOutcome, PluginInstallError> {
let resolved = find_installable_marketplace_plugin(
let resolved = match find_installable_marketplace_plugin(
&request.marketplace_path,
&request.plugin_name,
self.restriction_product,
)?;
) {
Ok(resolved) => resolved,
Err(err) => {
self.track_plugin_install_resolution_failed(&err);
return Err(err.into());
}
};
let plugin_id = resolved.plugin_id.as_key();
// This only forwards the backend mutation before the local install flow.
crate::remote_legacy::enable_remote_plugin(
if let Err(err) = crate::remote_legacy::enable_remote_plugin(
&remote_plugin_service_config(config),
auth,
&plugin_id,
)
.await
.map_err(PluginInstallError::from)?;
self.install_resolved_plugin(resolved).await
{
let err = PluginInstallError::from(err);
self.track_plugin_install_failed(
&resolved.plugin_id,
plugin_install_error_type(&err),
err.to_string(),
);
return Err(err);
}
let plugin_id = resolved.plugin_id.clone();
match self.install_resolved_plugin(resolved).await {
Ok(outcome) => Ok(outcome),
Err(err) => {
self.track_plugin_install_failed(
&plugin_id,
plugin_install_error_type(&err),
err.to_string(),
);
Err(err)
}
}
}
fn track_plugin_install_resolution_failed(&self, err: &MarketplaceError) {
let plugin_id = match err {
MarketplaceError::PluginNotFound {
plugin_name,
marketplace_name,
}
| MarketplaceError::PluginNotAvailable {
plugin_name,
marketplace_name,
} => PluginId::new(plugin_name.clone(), marketplace_name.clone()).ok(),
MarketplaceError::Io { .. }
| MarketplaceError::MarketplaceNotFound { .. }
| MarketplaceError::InvalidMarketplaceFile { .. }
| MarketplaceError::PluginsDisabled
| MarketplaceError::InvalidPlugin(_) => None,
};
if let Some(plugin_id) = plugin_id {
self.track_plugin_install_failed(
&plugin_id,
marketplace_error_type(err),
err.to_string(),
);
} else {
tracing::warn!(
error_type = %marketplace_error_type(err),
error = %err,
"plugin install failed while resolving marketplace plugin"
);
}
}
fn track_plugin_install_failed(
&self,
plugin_id: &PluginId,
error_type: &'static str,
error_message: String,
) {
tracing::warn!(
plugin_id = %plugin_id.as_key(),
error_type = %error_type,
error = %error_message,
"plugin install failed"
);
let analytics_events_client = match self.analytics_events_client.read() {
Ok(client) => client.clone(),
Err(err) => err.into_inner().clone(),
};
if let Some(analytics_events_client) = analytics_events_client {
analytics_events_client.track_plugin_install_failed(
PluginTelemetryMetadata::from_plugin_id(plugin_id),
error_type.to_string(),
);
}
}
async fn install_resolved_plugin(
@@ -2173,6 +2280,54 @@ impl PluginInstallError {
}
}
fn plugin_install_error_type(err: &PluginInstallError) -> &'static str {
match err {
PluginInstallError::Marketplace(err) => marketplace_error_type(err),
PluginInstallError::Remote(err) => remote_plugin_mutation_error_type(err),
PluginInstallError::Store(err) => plugin_store_error_type(err),
PluginInstallError::Config(_) => "config",
PluginInstallError::Join(_) => "join",
}
}
fn marketplace_error_type(err: &MarketplaceError) -> &'static str {
match err {
MarketplaceError::Io { .. } => "marketplace_io",
MarketplaceError::MarketplaceNotFound { .. } => "marketplace_not_found",
MarketplaceError::InvalidMarketplaceFile { .. } => "invalid_marketplace_file",
MarketplaceError::PluginNotFound { .. } => "plugin_not_found",
MarketplaceError::PluginNotAvailable { .. } => "plugin_not_available",
MarketplaceError::PluginsDisabled => "plugins_disabled",
MarketplaceError::InvalidPlugin(_) => "invalid_plugin",
}
}
fn remote_plugin_mutation_error_type(err: &RemotePluginMutationError) -> &'static str {
match err {
RemotePluginMutationError::AuthRequired => "remote_mutation_auth_required",
RemotePluginMutationError::UnsupportedAuthMode => "remote_mutation_unsupported_auth_mode",
RemotePluginMutationError::AuthToken(_) => "remote_mutation_auth_token",
RemotePluginMutationError::InvalidBaseUrl(_) => "remote_mutation_invalid_base_url",
RemotePluginMutationError::InvalidBaseUrlPath => "remote_mutation_invalid_base_url_path",
RemotePluginMutationError::Request { .. } => "remote_mutation_request",
RemotePluginMutationError::UnexpectedStatus { .. } => "remote_mutation_unexpected_status",
RemotePluginMutationError::Decode { .. } => "remote_mutation_decode",
RemotePluginMutationError::UnexpectedPluginId { .. } => {
"remote_mutation_unexpected_plugin_id"
}
RemotePluginMutationError::UnexpectedEnabledState { .. } => {
"remote_mutation_unexpected_enabled_state"
}
}
}
fn plugin_store_error_type(err: &PluginStoreError) -> &'static str {
match err {
PluginStoreError::Io { .. } => "store_io",
PluginStoreError::Invalid(_) => "store_invalid",
}
}
#[derive(Debug, thiserror::Error)]
pub enum PluginUninstallError {
#[error("{0}")]
+14 -8
View File
@@ -544,20 +544,26 @@ fn resolve_local_plugin_source_path(
marketplace_path: &AbsolutePathBuf,
path: &str,
) -> Result<AbsolutePathBuf, MarketplaceError> {
let Some(path) = path.strip_prefix("./") else {
match path {
"" => {
return Err(MarketplaceError::InvalidMarketplaceFile {
path: marketplace_path.to_path_buf(),
message: "local plugin source path must not be empty".to_string(),
});
}
"." | "./" => return marketplace_root_dir(marketplace_path),
_ => {}
}
// Non-root local sources must keep the explicit `./` prefix and remain normalized.
let Some(relative_path) = path.strip_prefix("./") else {
return Err(MarketplaceError::InvalidMarketplaceFile {
path: marketplace_path.to_path_buf(),
message: "local plugin source path must start with `./`".to_string(),
});
};
if path.is_empty() {
return Err(MarketplaceError::InvalidMarketplaceFile {
path: marketplace_path.to_path_buf(),
message: "local plugin source path must not be empty".to_string(),
});
}
let relative_source_path = Path::new(path);
let relative_source_path = Path::new(relative_path);
if relative_source_path
.components()
.any(|component| !matches!(component, Component::Normal(_)))
+114 -24
View File
@@ -420,6 +420,92 @@ fn list_marketplaces_supports_alternate_manifest_layout() {
);
}
#[test]
fn list_marketplaces_supports_repo_root_local_plugin_sources() {
for path in [".", "./"] {
let tmp = tempdir().unwrap();
let repo_root = tmp.path().join("repo");
fs::create_dir_all(repo_root.join(".git")).unwrap();
fs::create_dir_all(repo_root.join(".agents/plugins")).unwrap();
fs::create_dir_all(repo_root.join(".codex-plugin")).unwrap();
fs::write(
repo_root.join(".agents/plugins/marketplace.json"),
format!(
r#"{{
"name": "repo-root-marketplace",
"plugins": [
{{
"name": "repo-root-plugin",
"source": {{
"source": "local",
"path": "{path}"
}}
}}
]
}}"#
),
)
.unwrap();
fs::write(
repo_root.join(".codex-plugin/plugin.json"),
r#"{
"name":"repo-root-plugin",
"interface": {
"displayName": "Repo Root Plugin"
}
}"#,
)
.unwrap();
let marketplaces = list_marketplaces_with_home(
&[AbsolutePathBuf::try_from(repo_root.clone()).unwrap()],
/*home_dir*/ None,
)
.unwrap()
.marketplaces;
assert_eq!(
marketplaces,
vec![Marketplace {
name: "repo-root-marketplace".to_string(),
path: AbsolutePathBuf::try_from(repo_root.join(".agents/plugins/marketplace.json"))
.unwrap(),
interface: None,
plugins: vec![MarketplacePlugin {
name: "repo-root-plugin".to_string(),
local_version: None,
source: MarketplacePluginSource::Local {
path: AbsolutePathBuf::try_from(repo_root).unwrap(),
},
policy: MarketplacePluginPolicy {
installation: MarketplacePluginInstallPolicy::Available,
authentication: MarketplacePluginAuthPolicy::OnInstall,
products: None,
},
interface: Some(PluginManifestInterface {
display_name: Some("Repo Root Plugin".to_string()),
short_description: None,
long_description: None,
developer_name: None,
category: None,
capabilities: Vec::new(),
website_url: None,
privacy_policy_url: None,
terms_of_service_url: None,
default_prompt: None,
brand_color: None,
composer_icon: None,
logo: None,
screenshots: Vec::new(),
}),
keywords: Vec::new(),
}],
}]
);
}
}
#[test]
fn list_marketplaces_includes_plugins_without_discoverable_manifest() {
let tmp = tempdir().unwrap();
@@ -1423,37 +1509,41 @@ fn list_marketplaces_ignores_plugin_interface_assets_without_dot_slash() {
#[test]
fn find_marketplace_plugin_skips_invalid_local_paths() {
let tmp = tempdir().unwrap();
let repo_root = tmp.path().join("repo");
fs::create_dir_all(repo_root.join(".git")).unwrap();
fs::create_dir_all(repo_root.join(".agents/plugins")).unwrap();
fs::write(
repo_root.join(".agents/plugins/marketplace.json"),
r#"{
for path in ["", "plugin-1", "././", "./plugins/../", "../plugin-1"] {
let tmp = tempdir().unwrap();
let repo_root = tmp.path().join("repo");
fs::create_dir_all(repo_root.join(".git")).unwrap();
fs::create_dir_all(repo_root.join(".agents/plugins")).unwrap();
fs::write(
repo_root.join(".agents/plugins/marketplace.json"),
format!(
r#"{{
"name": "codex-curated",
"plugins": [
{
{{
"name": "local-plugin",
"source": {
"source": {{
"source": "local",
"path": "../plugin-1"
}
}
"path": "{path}"
}}
}}
]
}"#,
)
.unwrap();
}}"#
),
)
.unwrap();
let err = find_marketplace_plugin(
&AbsolutePathBuf::try_from(repo_root.join(".agents/plugins/marketplace.json")).unwrap(),
"local-plugin",
)
.unwrap_err();
let err = find_marketplace_plugin(
&AbsolutePathBuf::try_from(repo_root.join(".agents/plugins/marketplace.json")).unwrap(),
"local-plugin",
)
.unwrap_err();
assert_eq!(
err.to_string(),
"plugin `local-plugin` was not found in marketplace `codex-curated`"
);
assert_eq!(
err.to_string(),
"plugin `local-plugin` was not found in marketplace `codex-curated`"
);
}
}
#[test]
+2
View File
@@ -27,6 +27,7 @@ use std::fs;
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;
use tracing::instrument;
use url::Url;
mod catalog_cache;
@@ -805,6 +806,7 @@ pub async fn fetch_and_cache_global_remote_plugin_catalog(
Ok(())
}
#[instrument(level = "trace", skip_all)]
pub async fn fetch_recommended_plugins(
config: &RemotePluginServiceConfig,
auth: Option<&CodexAuth>,
+1 -1
View File
@@ -878,7 +878,7 @@ async fn spawn_agent_can_fork_parent_thread_history_with_sanitized_items() {
assistant_message("parent final answer", Some(MessagePhase::FinalAnswer)),
assistant_message("parent unknown phase", /*phase*/ None),
ResponseItem::Reasoning {
id: "parent-reasoning".to_string(),
id: Some("parent-reasoning".to_string()),
summary: Vec::new(),
content: None,
encrypted_content: None,
+13 -1
View File
@@ -35,12 +35,24 @@ pub(crate) async fn apply_patch(
file_system_sandbox_policy: &FileSystemSandboxPolicy,
action: ApplyPatchAction,
) -> InternalApplyPatchInvocation {
// TODO(anp): Migrate patch safety checks to PathUri.
let cwd = match action.cwd.to_abs_path() {
Ok(cwd) => cwd,
Err(err) => {
return InternalApplyPatchInvocation::Output(Err(FunctionCallError::RespondToModel(
format!(
"patch cwd `{}` is not native to the Codex host: {err}",
action.cwd
),
)));
}
};
match assess_patch_safety(
&action,
turn_context.approval_policy.value(),
&turn_context.permission_profile(),
file_system_sandbox_policy,
&action.cwd,
&cwd,
turn_context.windows_sandbox_level,
) {
SafetyCheck::AutoApprove {
+4
View File
@@ -23,6 +23,7 @@ fn prompt_with_image_outputs() -> Prompt {
metadata: None,
},
ResponseItem::FunctionCallOutput {
id: None,
call_id: "function-call".to_string(),
output: FunctionCallOutputPayload::from_content_items(vec![
FunctionCallOutputContentItem::InputImage {
@@ -33,6 +34,7 @@ fn prompt_with_image_outputs() -> Prompt {
metadata: None,
},
ResponseItem::CustomToolCallOutput {
id: None,
call_id: "custom-call".to_string(),
name: None,
output: FunctionCallOutputPayload::from_content_items(vec![
@@ -69,6 +71,7 @@ fn responses_lite_request_copies_strip_image_details() {
metadata: None,
},
ResponseItem::FunctionCallOutput {
id: None,
call_id: "function-call".to_string(),
output: FunctionCallOutputPayload::from_content_items(vec![
FunctionCallOutputContentItem::InputImage {
@@ -79,6 +82,7 @@ fn responses_lite_request_copies_strip_image_details() {
metadata: None,
},
ResponseItem::CustomToolCallOutput {
id: None,
call_id: "custom-call".to_string(),
name: None,
output: FunctionCallOutputPayload::from_content_items(vec![
+2 -1
View File
@@ -41,6 +41,7 @@ use codex_thread_store::ThreadMetadataPatch;
use codex_thread_store::ThreadStoreError;
use codex_thread_store::ThreadStoreResult;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use rmcp::model::ReadResourceRequestParams;
use std::collections::BTreeMap;
use std::collections::HashMap;
@@ -164,7 +165,7 @@ pub struct BackgroundTerminalInfo {
pub item_id: String,
pub process_id: String,
pub command: String,
pub cwd: AbsolutePathBuf,
pub cwd: PathUri,
}
/// Conduit for the bidirectional stream of messages that compose a thread
+5
View File
@@ -403,20 +403,24 @@ pub(crate) fn trim_function_call_history_to_fit_context_window(
fn rewritten_output_for_context_window(item: &ResponseItem) -> Option<ResponseItem> {
Some(match item {
ResponseItem::FunctionCallOutput {
id,
call_id,
output,
metadata,
} => ResponseItem::FunctionCallOutput {
id: id.clone(),
call_id: call_id.clone(),
output: truncated_output_payload(output),
metadata: metadata.clone(),
},
ResponseItem::CustomToolCallOutput {
id,
call_id,
name,
output,
metadata,
} => ResponseItem::CustomToolCallOutput {
id: id.clone(),
call_id: call_id.clone(),
name: name.clone(),
output: truncated_output_payload(output),
@@ -429,6 +433,7 @@ fn rewritten_output_for_context_window(item: &ResponseItem) -> Option<ResponseIt
metadata,
..
} => ResponseItem::ToolSearchOutput {
id: item.id().map(str::to_string),
call_id: call_id.clone(),
status: status.clone(),
execution: execution.clone(),
+9 -1
View File
@@ -231,7 +231,10 @@ async fn run_remote_compact_task_inner_impl(
)
.await?;
let mut input = prompt_input.clone();
input.push(ResponseItem::CompactionTrigger { metadata: None });
input.push(ResponseItem::CompactionTrigger {
id: None,
metadata: None,
});
let prompt = Prompt {
input,
tools: tool_router.model_visible_specs(),
@@ -609,11 +612,13 @@ mod tests {
metadata: None,
},
ResponseItem::Compaction {
id: None,
encrypted_content: "old".to_string(),
metadata: None,
},
];
let output = ResponseItem::Compaction {
id: None,
encrypted_content: "new".to_string(),
metadata: None,
};
@@ -642,6 +647,7 @@ mod tests {
new.clone(),
];
let output = ResponseItem::Compaction {
id: None,
encrypted_content: "new".to_string(),
metadata: None,
};
@@ -673,6 +679,7 @@ mod tests {
metadata: None,
}];
let output = ResponseItem::Compaction {
id: None,
encrypted_content: "new".to_string(),
metadata: None,
};
@@ -800,6 +807,7 @@ mod tests {
#[tokio::test]
async fn collect_compaction_output_accepts_additional_output_items() {
let compaction = ResponseItem::Compaction {
id: None,
encrypted_content: "encrypted".to_string(),
metadata: None,
};
+2
View File
@@ -654,6 +654,7 @@ fn insert_initial_context_before_last_real_user_or_summary_keeps_summary_last()
#[test]
fn insert_initial_context_before_last_real_user_or_summary_keeps_compaction_last() {
let compacted_history = vec![ResponseItem::Compaction {
id: None,
encrypted_content: "encrypted".to_string(),
metadata: None,
}];
@@ -680,6 +681,7 @@ fn insert_initial_context_before_last_real_user_or_summary_keeps_compaction_last
metadata: None,
},
ResponseItem::Compaction {
id: None,
encrypted_content: "encrypted".to_string(),
metadata: None,
},
+1
View File
@@ -94,6 +94,7 @@ pub(crate) async fn list_accessible_and_enabled_connectors_from_manager(
.collect()
}
#[instrument(level = "trace", skip_all)]
pub(crate) async fn list_tool_suggest_discoverable_tools_with_auth(
config: &Config,
plugins_manager: &PluginsManager,
@@ -339,20 +339,24 @@ impl ContextManager {
let policy_with_serialization_budget = policy * 1.2;
match item {
ResponseItem::FunctionCallOutput {
id,
call_id,
output,
metadata,
} => ResponseItem::FunctionCallOutput {
id: id.clone(),
call_id: call_id.clone(),
output: truncate_function_output_payload(output, policy_with_serialization_budget),
metadata: metadata.clone(),
},
ResponseItem::CustomToolCallOutput {
id,
call_id,
name,
output,
metadata,
} => ResponseItem::CustomToolCallOutput {
id: id.clone(),
call_id: call_id.clone(),
name: name.clone(),
output: truncate_function_output_payload(output, policy_with_serialization_budget),
@@ -154,6 +154,7 @@ fn reference_context_item() -> TurnContextItem {
fn custom_tool_call_output(call_id: &str, output: &str) -> ResponseItem {
ResponseItem::CustomToolCallOutput {
id: None,
call_id: call_id.to_string(),
name: None,
output: FunctionCallOutputPayload::from_text(output.to_string()),
@@ -163,7 +164,7 @@ fn custom_tool_call_output(call_id: &str, output: &str) -> ResponseItem {
fn reasoning_msg(text: &str) -> ResponseItem {
ResponseItem::Reasoning {
id: String::new(),
id: None,
summary: vec![ReasoningItemReasoningSummary::SummaryText {
text: "summary".to_string(),
}],
@@ -177,7 +178,7 @@ fn reasoning_msg(text: &str) -> ResponseItem {
fn reasoning_with_encrypted_content(len: usize) -> ResponseItem {
ResponseItem::Reasoning {
id: String::new(),
id: None,
summary: vec![ReasoningItemReasoningSummary::SummaryText {
text: "summary".to_string(),
}],
@@ -222,7 +223,7 @@ fn filters_non_api_messages() {
items,
vec![
ResponseItem::Reasoning {
id: String::new(),
id: None,
summary: vec![ReasoningItemReasoningSummary::SummaryText {
text: "summary".to_string(),
}],
@@ -409,6 +410,7 @@ fn for_prompt_strips_images_when_model_does_not_support_images() {
metadata: None,
},
ResponseItem::FunctionCallOutput {
id: None,
call_id: "call-1".to_string(),
output: FunctionCallOutputPayload::from_content_items(vec![
FunctionCallOutputContentItem::InputText {
@@ -430,6 +432,7 @@ fn for_prompt_strips_images_when_model_does_not_support_images() {
metadata: None,
},
ResponseItem::CustomToolCallOutput {
id: None,
call_id: "tool-1".to_string(),
name: None,
output: FunctionCallOutputPayload::from_content_items(vec![
@@ -476,6 +479,7 @@ fn for_prompt_strips_images_when_model_does_not_support_images() {
metadata: None,
},
ResponseItem::FunctionCallOutput {
id: None,
call_id: "call-1".to_string(),
output: FunctionCallOutputPayload::from_content_items(vec![
FunctionCallOutputContentItem::InputText {
@@ -497,6 +501,7 @@ fn for_prompt_strips_images_when_model_does_not_support_images() {
metadata: None,
},
ResponseItem::CustomToolCallOutput {
id: None,
call_id: "tool-1".to_string(),
name: None,
output: FunctionCallOutputPayload::from_content_items(vec![
@@ -544,7 +549,7 @@ fn for_prompt_strips_images_when_model_does_not_support_images() {
fn for_prompt_preserves_image_generation_calls_when_images_are_supported() {
let history = create_history_with_items(vec![
ResponseItem::ImageGenerationCall {
id: "ig_123".to_string(),
id: Some("ig_123".to_string()),
status: "generating".to_string(),
revised_prompt: Some("lobster".to_string()),
result: "Zm9v".to_string(),
@@ -565,7 +570,7 @@ fn for_prompt_preserves_image_generation_calls_when_images_are_supported() {
history.for_prompt(&default_input_modalities()),
vec![
ResponseItem::ImageGenerationCall {
id: "ig_123".to_string(),
id: Some("ig_123".to_string()),
status: "generating".to_string(),
revised_prompt: Some("lobster".to_string()),
result: "Zm9v".to_string(),
@@ -597,7 +602,7 @@ fn for_prompt_clears_image_generation_result_when_images_are_unsupported() {
metadata: None,
},
ResponseItem::ImageGenerationCall {
id: "ig_123".to_string(),
id: Some("ig_123".to_string()),
status: "completed".to_string(),
revised_prompt: Some("lobster".to_string()),
result: "Zm9v".to_string(),
@@ -618,7 +623,7 @@ fn for_prompt_clears_image_generation_result_when_images_are_unsupported() {
metadata: None,
},
ResponseItem::ImageGenerationCall {
id: "ig_123".to_string(),
id: Some("ig_123".to_string()),
status: "completed".to_string(),
revised_prompt: Some("lobster".to_string()),
result: String::new(),
@@ -662,6 +667,7 @@ fn remove_first_item_removes_matching_output_for_function_call() {
metadata: None,
},
ResponseItem::FunctionCallOutput {
id: None,
call_id: "call-1".to_string(),
output: FunctionCallOutputPayload::from_text("ok".to_string()),
metadata: None,
@@ -676,6 +682,7 @@ fn remove_first_item_removes_matching_output_for_function_call() {
fn remove_first_item_removes_matching_call_for_output() {
let items = vec![
ResponseItem::FunctionCallOutput {
id: None,
call_id: "call-2".to_string(),
output: FunctionCallOutputPayload::from_text("ok".to_string()),
metadata: None,
@@ -699,6 +706,7 @@ fn replace_last_turn_images_replaces_tool_output_images() {
let items = vec![
user_input_text_msg("hi"),
ResponseItem::FunctionCallOutput {
id: None,
call_id: "call-1".to_string(),
output: FunctionCallOutputPayload {
body: FunctionCallOutputBody::ContentItems(vec![
@@ -721,6 +729,7 @@ fn replace_last_turn_images_replaces_tool_output_images() {
vec![
user_input_text_msg("hi"),
ResponseItem::FunctionCallOutput {
id: None,
call_id: "call-1".to_string(),
output: FunctionCallOutputPayload {
body: FunctionCallOutputBody::ContentItems(vec![
@@ -771,6 +780,7 @@ fn remove_first_item_handles_local_shell_pair() {
metadata: None,
},
ResponseItem::FunctionCallOutput {
id: None,
call_id: "call-3".to_string(),
output: FunctionCallOutputPayload::from_text("ok".to_string()),
metadata: None,
@@ -998,6 +1008,7 @@ fn remove_first_item_handles_custom_tool_pair() {
metadata: None,
},
ResponseItem::CustomToolCallOutput {
id: None,
call_id: "tool-1".to_string(),
name: None,
output: FunctionCallOutputPayload::from_text("ok".to_string()),
@@ -1026,6 +1037,7 @@ fn normalization_retains_local_shell_outputs() {
metadata: None,
},
ResponseItem::FunctionCallOutput {
id: None,
call_id: "shell-1".to_string(),
output: FunctionCallOutputPayload::from_text("Total output lines: 1\n\nok".to_string()),
metadata: None,
@@ -1047,6 +1059,7 @@ fn record_items_truncates_function_call_output_content() {
let long_line = "a very long line to trigger truncation\n";
let long_output = long_line.repeat(2_500);
let item = ResponseItem::FunctionCallOutput {
id: None,
call_id: "call-100".to_string(),
output: FunctionCallOutputPayload {
body: FunctionCallOutputBody::Text(long_output.clone()),
@@ -1086,6 +1099,7 @@ fn record_items_truncates_custom_tool_call_output_content() {
let line = "custom output that is very long\n";
let long_output = line.repeat(2_500);
let item = ResponseItem::CustomToolCallOutput {
id: None,
call_id: "tool-200".to_string(),
name: None,
output: FunctionCallOutputPayload::from_text(long_output.clone()),
@@ -1118,6 +1132,7 @@ fn record_items_respects_custom_token_limit() {
let policy = TruncationPolicy::Tokens(10);
let long_output = "tokenized content repeated many times ".repeat(200);
let item = ResponseItem::FunctionCallOutput {
id: None,
call_id: "call-custom-limit".to_string(),
output: FunctionCallOutputPayload {
body: FunctionCallOutputBody::Text(long_output),
@@ -1261,6 +1276,7 @@ fn normalize_adds_missing_output_for_function_call() {
metadata: None,
},
ResponseItem::FunctionCallOutput {
id: None,
call_id: "call-x".to_string(),
output: FunctionCallOutputPayload::from_text("aborted".to_string()),
metadata: None,
@@ -1296,6 +1312,7 @@ fn normalize_adds_missing_output_for_custom_tool_call() {
metadata: None,
},
ResponseItem::CustomToolCallOutput {
id: None,
call_id: "tool-x".to_string(),
name: None,
output: FunctionCallOutputPayload::from_text("aborted".to_string()),
@@ -1342,6 +1359,7 @@ fn normalize_adds_missing_output_for_local_shell_call_with_id() {
metadata: None,
},
ResponseItem::FunctionCallOutput {
id: None,
call_id: "shell-1".to_string(),
output: FunctionCallOutputPayload::from_text("aborted".to_string()),
metadata: None,
@@ -1354,6 +1372,7 @@ fn normalize_adds_missing_output_for_local_shell_call_with_id() {
#[test]
fn normalize_removes_orphan_function_call_output() {
let items = vec![ResponseItem::FunctionCallOutput {
id: None,
call_id: "orphan-1".to_string(),
output: FunctionCallOutputPayload::from_text("ok".to_string()),
metadata: None,
@@ -1369,6 +1388,7 @@ fn normalize_removes_orphan_function_call_output() {
#[test]
fn normalize_removes_orphan_custom_tool_call_output() {
let items = vec![ResponseItem::CustomToolCallOutput {
id: None,
call_id: "orphan-2".to_string(),
name: None,
output: FunctionCallOutputPayload::from_text("ok".to_string()),
@@ -1396,6 +1416,7 @@ fn normalize_mixed_inserts_and_removals() {
},
// Orphan output that should be removed
ResponseItem::FunctionCallOutput {
id: None,
call_id: "c2".to_string(),
output: FunctionCallOutputPayload::from_text("ok".to_string()),
metadata: None,
@@ -1440,6 +1461,7 @@ fn normalize_mixed_inserts_and_removals() {
metadata: None,
},
ResponseItem::FunctionCallOutput {
id: None,
call_id: "c1".to_string(),
output: FunctionCallOutputPayload::from_text("aborted".to_string()),
metadata: None,
@@ -1453,6 +1475,7 @@ fn normalize_mixed_inserts_and_removals() {
metadata: None,
},
ResponseItem::CustomToolCallOutput {
id: None,
call_id: "t1".to_string(),
name: None,
output: FunctionCallOutputPayload::from_text("aborted".to_string()),
@@ -1472,6 +1495,7 @@ fn normalize_mixed_inserts_and_removals() {
metadata: None,
},
ResponseItem::FunctionCallOutput {
id: None,
call_id: "s1".to_string(),
output: FunctionCallOutputPayload::from_text("aborted".to_string()),
metadata: None,
@@ -1504,6 +1528,7 @@ fn normalize_adds_missing_output_for_function_call_inserts_output() {
metadata: None,
},
ResponseItem::FunctionCallOutput {
id: None,
call_id: "call-x".to_string(),
output: FunctionCallOutputPayload::from_text("aborted".to_string()),
metadata: None,
@@ -1538,6 +1563,7 @@ fn normalize_adds_missing_output_for_tool_search_call() {
metadata: None,
},
ResponseItem::ToolSearchOutput {
id: None,
call_id: Some("search-call-x".to_string()),
status: "completed".to_string(),
execution: "client".to_string(),
@@ -1590,6 +1616,7 @@ fn normalize_adds_missing_output_for_local_shell_call_with_id_panics_in_debug()
#[should_panic]
fn normalize_removes_orphan_function_call_output_panics_in_debug() {
let items = vec![ResponseItem::FunctionCallOutput {
id: None,
call_id: "orphan-1".to_string(),
output: FunctionCallOutputPayload::from_text("ok".to_string()),
metadata: None,
@@ -1603,6 +1630,7 @@ fn normalize_removes_orphan_function_call_output_panics_in_debug() {
#[should_panic]
fn normalize_removes_orphan_custom_tool_call_output_panics_in_debug() {
let items = vec![ResponseItem::CustomToolCallOutput {
id: None,
call_id: "orphan-2".to_string(),
name: None,
output: FunctionCallOutputPayload::from_text("ok".to_string()),
@@ -1616,6 +1644,7 @@ fn normalize_removes_orphan_custom_tool_call_output_panics_in_debug() {
#[test]
fn normalize_removes_orphan_client_tool_search_output() {
let items = vec![ResponseItem::ToolSearchOutput {
id: None,
call_id: Some("orphan-search".to_string()),
status: "completed".to_string(),
execution: "client".to_string(),
@@ -1634,6 +1663,7 @@ fn normalize_removes_orphan_client_tool_search_output() {
#[should_panic]
fn normalize_removes_orphan_client_tool_search_output_panics_in_debug() {
let items = vec![ResponseItem::ToolSearchOutput {
id: None,
call_id: Some("orphan-search".to_string()),
status: "completed".to_string(),
execution: "client".to_string(),
@@ -1647,6 +1677,7 @@ fn normalize_removes_orphan_client_tool_search_output_panics_in_debug() {
#[test]
fn normalize_keeps_server_tool_search_output_without_matching_call() {
let items = vec![ResponseItem::ToolSearchOutput {
id: None,
call_id: Some("server-search".to_string()),
status: "completed".to_string(),
execution: "server".to_string(),
@@ -1660,6 +1691,7 @@ fn normalize_keeps_server_tool_search_output_without_matching_call() {
assert_eq!(
h.raw_items(),
vec![ResponseItem::ToolSearchOutput {
id: None,
call_id: Some("server-search".to_string()),
status: "completed".to_string(),
execution: "server".to_string(),
@@ -1683,6 +1715,7 @@ fn normalize_mixed_inserts_and_removals_panics_in_debug() {
metadata: None,
},
ResponseItem::FunctionCallOutput {
id: None,
call_id: "c2".to_string(),
output: FunctionCallOutputPayload::from_text("ok".to_string()),
metadata: None,
@@ -1757,6 +1790,7 @@ fn image_data_url_payload_does_not_dominate_function_call_output_estimate() {
let payload = "B".repeat(50_000);
let image_url = format!("data:image/png;base64,{payload}");
let item = ResponseItem::FunctionCallOutput {
id: None,
call_id: "call-abc".to_string(),
output: FunctionCallOutputPayload::from_content_items(vec![
FunctionCallOutputContentItem::InputText {
@@ -1783,6 +1817,7 @@ fn image_data_url_payload_does_not_dominate_custom_tool_call_output_estimate() {
let payload = "C".repeat(50_000);
let image_url = format!("data:image/png;base64,{payload}");
let item = ResponseItem::CustomToolCallOutput {
id: None,
call_id: "call-js-repl".to_string(),
name: None,
output: FunctionCallOutputPayload::from_content_items(vec![
@@ -1818,6 +1853,7 @@ fn non_base64_image_urls_are_unchanged() {
metadata: None,
};
let function_output_item = ResponseItem::FunctionCallOutput {
id: None,
call_id: "call-1".to_string(),
output: FunctionCallOutputPayload::from_content_items(vec![
FunctionCallOutputContentItem::InputImage {
@@ -1842,6 +1878,7 @@ fn non_base64_image_urls_are_unchanged() {
fn encrypted_function_output_uses_plaintext_byte_estimate() {
let encrypted_content = "A".repeat(1_868);
let item = ResponseItem::FunctionCallOutput {
id: None,
call_id: "call-encrypted".to_string(),
output: FunctionCallOutputPayload::from_content_items(vec![
FunctionCallOutputContentItem::EncryptedContent {
@@ -1883,6 +1920,7 @@ fn non_image_base64_data_url_is_unchanged() {
let payload = "C".repeat(4_096);
let image_url = format!("data:application/octet-stream;base64,{payload}");
let item = ResponseItem::FunctionCallOutput {
id: None,
call_id: "call-octet".to_string(),
output: FunctionCallOutputPayload::from_content_items(vec![
FunctionCallOutputContentItem::InputImage {
@@ -1971,6 +2009,7 @@ fn original_detail_images_scale_with_dimensions() {
let payload = BASE64_STANDARD.encode(bytes.get_ref());
let image_url = format!("data:image/png;base64,{payload}");
let item = ResponseItem::FunctionCallOutput {
id: None,
call_id: "call-original".to_string(),
output: FunctionCallOutputPayload::from_content_items(vec![
FunctionCallOutputContentItem::InputImage {
@@ -2002,6 +2041,7 @@ fn original_detail_images_are_capped_at_max_patch_count() {
let payload = BASE64_STANDARD.encode(bytes.get_ref());
let image_url = format!("data:image/png;base64,{payload}");
let item = ResponseItem::FunctionCallOutput {
id: None,
call_id: "call-original-capped".to_string(),
output: FunctionCallOutputPayload::from_content_items(vec![
FunctionCallOutputContentItem::InputImage {
@@ -2036,6 +2076,7 @@ fn original_detail_webp_images_scale_with_dimensions() {
let payload = BASE64_STANDARD.encode(bytes.get_ref());
let image_url = format!("data:image/webp;base64,{payload}");
let item = ResponseItem::FunctionCallOutput {
id: None,
call_id: "call-original-webp".to_string(),
output: FunctionCallOutputPayload::from_content_items(vec![
FunctionCallOutputContentItem::InputImage {
@@ -47,6 +47,7 @@ pub(crate) fn ensure_call_outputs_present(items: &mut Vec<ResponseItem>) {
missing_outputs_to_insert.push((
idx,
ResponseItem::FunctionCallOutput {
id: None,
call_id: call_id.clone(),
output: FunctionCallOutputPayload::from_text("aborted".to_string()),
metadata: None,
@@ -61,6 +62,7 @@ pub(crate) fn ensure_call_outputs_present(items: &mut Vec<ResponseItem>) {
missing_outputs_to_insert.push((
idx,
ResponseItem::ToolSearchOutput {
id: None,
call_id: Some(call_id.clone()),
status: "completed".to_string(),
execution: "client".to_string(),
@@ -78,6 +80,7 @@ pub(crate) fn ensure_call_outputs_present(items: &mut Vec<ResponseItem>) {
missing_outputs_to_insert.push((
idx,
ResponseItem::CustomToolCallOutput {
id: None,
call_id: call_id.clone(),
name: None,
output: FunctionCallOutputPayload::from_text("aborted".to_string()),
@@ -96,6 +99,7 @@ pub(crate) fn ensure_call_outputs_present(items: &mut Vec<ResponseItem>) {
missing_outputs_to_insert.push((
idx,
ResponseItem::FunctionCallOutput {
id: None,
call_id: call_id.clone(),
output: FunctionCallOutputPayload::from_text("aborted".to_string()),
metadata: None,
+2 -2
View File
@@ -178,7 +178,7 @@ pub fn parse_turn_item(item: &ResponseItem) -> Option<TurnItem> {
})
.collect();
Some(TurnItem::Reasoning(ReasoningItem {
id: id.clone(),
id: id.clone().unwrap_or_default(),
summary_text,
raw_content,
}))
@@ -202,7 +202,7 @@ pub fn parse_turn_item(item: &ResponseItem) -> Option<TurnItem> {
..
} => Some(TurnItem::ImageGeneration(
codex_protocol::items::ImageGenerationItem {
id: id.clone(),
id: id.clone()?,
status: status.clone(),
revised_prompt: revised_prompt.clone(),
result: result.clone(),
+2 -2
View File
@@ -391,7 +391,7 @@ fn parses_agent_message() {
#[test]
fn parses_reasoning_summary_and_raw_content() {
let item = ResponseItem::Reasoning {
id: "reasoning_1".to_string(),
id: Some("reasoning_1".to_string()),
summary: vec![
ReasoningItemReasoningSummary::SummaryText {
text: "Step 1".to_string(),
@@ -424,7 +424,7 @@ fn parses_reasoning_summary_and_raw_content() {
#[test]
fn parses_reasoning_including_raw_content() {
let item = ResponseItem::Reasoning {
id: "reasoning_2".to_string(),
id: Some("reasoning_2".to_string()),
summary: vec![ReasoningItemReasoningSummary::SummaryText {
text: "Summarized step".to_string(),
}],
+10 -1
View File
@@ -381,7 +381,7 @@ pub fn build_exec_request(
})
.map(|request| {
let windows_sandbox_workspace_roots = if windows_sandbox_workspace_roots.is_empty() {
vec![request.sandbox_policy_cwd.clone()]
vec![sandbox_cwd.clone()]
} else {
windows_sandbox_workspace_roots.to_vec()
};
@@ -440,6 +440,15 @@ pub(crate) async fn execute_exec_request(
arg0,
} = exec_request;
// TODO(anp): Keep PathUri through the local process launch boundary.
let cwd = cwd
.to_abs_path()
.map_err(|err| CodexErr::InvalidRequest(format!("invalid exec cwd: {err}")))?;
// TODO(anp): Keep PathUri through the Windows sandbox launch boundary.
let windows_sandbox_policy_cwd = windows_sandbox_policy_cwd
.to_abs_path()
.map_err(|err| CodexErr::InvalidRequest(format!("invalid sandbox cwd: {err}")))?;
let params = ExecParams {
command,
cwd,
+2
View File
@@ -309,6 +309,7 @@ async fn seed_guardian_parent_history(session: &Arc<Session>, turn: &Arc<TurnCon
metadata: None,
},
ResponseItem::FunctionCallOutput {
id: None,
call_id: "call-1".to_string(),
output: codex_protocol::models::FunctionCallOutputPayload::from_text(
"repo visibility: public".to_string(),
@@ -827,6 +828,7 @@ fn collect_guardian_transcript_entries_includes_recent_tool_calls_and_output() {
metadata: None,
},
ResponseItem::FunctionCallOutput {
id: None,
call_id: "call-1".to_string(),
output: codex_protocol::models::FunctionCallOutputPayload::from_text(
"repo is public".to_string(),
@@ -106,6 +106,7 @@ fn preparation_replaces_only_failed_tool_images_and_preserves_metadata() {
let (valid_image_url, _) = png_data_url(/*width*/ 64, /*height*/ 32);
let expected_valid_image_url = valid_image_url.clone();
let mut items = vec![ResponseItem::CustomToolCallOutput {
id: None,
call_id: "call-1".to_string(),
name: None,
output: FunctionCallOutputPayload {
@@ -140,6 +141,7 @@ fn preparation_replaces_only_failed_tool_images_and_preserves_metadata() {
assert_eq!(
items,
vec![ResponseItem::CustomToolCallOutput {
id: None,
call_id: "call-1".to_string(),
name: None,
output: FunctionCallOutputPayload {
@@ -47,6 +47,10 @@ fn stored_thread(cwd: &str, title: &str, first_user_message: &str) -> StoredThre
.timestamp_opt(1_709_251_200, 0)
.single()
.expect("valid timestamp"),
recency_at: Utc
.timestamp_opt(1_709_251_200, 0)
.single()
.expect("valid timestamp"),
archived_at: None,
cwd: PathBuf::from(cwd),
cli_version: "test".to_string(),
+61 -3
View File
@@ -30,6 +30,7 @@ use codex_login::read_openai_api_key_from_env;
use codex_model_provider_info::ModelProviderInfo;
use codex_protocol::error::CodexErr;
use codex_protocol::error::Result as CodexResult;
use codex_protocol::models::MessagePhase;
use codex_protocol::protocol::CodexErrorInfo;
use codex_protocol::protocol::ConversationAudioParams;
use codex_protocol::protocol::ConversationSpeechParams;
@@ -107,8 +108,10 @@ struct RealtimeHandoffState {
output_tx: Sender<RealtimeOutbound>,
active_handoff: Arc<Mutex<Option<String>>>,
last_output_text: Arc<Mutex<Option<String>>>,
client_managed_handoffs: bool,
codex_responses_as_items: bool,
codex_response_item_prefix: Option<String>,
codex_response_handoff_prefix: Option<String>,
session_kind: RealtimeSessionKind,
}
@@ -116,6 +119,7 @@ struct RealtimeHandoffState {
enum RealtimeOutbound {
StandaloneHandoff { text: String },
HandoffUpdate { handoff_id: String, text: String },
HandoffAppend { handoff_id: String, text: String },
CompletedHandoff { handoff_id: String, text: String },
ConversationItem { text: String },
HandoffCompleteAck { handoff_id: String },
@@ -210,16 +214,20 @@ struct RealtimeInputChannels {
impl RealtimeHandoffState {
fn new(
output_tx: Sender<RealtimeOutbound>,
client_managed_handoffs: bool,
codex_responses_as_items: bool,
codex_response_item_prefix: Option<String>,
codex_response_handoff_prefix: Option<String>,
session_kind: RealtimeSessionKind,
) -> Self {
Self {
output_tx,
active_handoff: Arc::new(Mutex::new(None)),
last_output_text: Arc::new(Mutex::new(None)),
client_managed_handoffs,
codex_responses_as_items,
codex_response_item_prefix,
codex_response_handoff_prefix,
session_kind,
}
}
@@ -240,8 +248,10 @@ struct RealtimeStart {
api_provider: ApiProvider,
architecture: RealtimeConversationArchitecture,
extra_headers: Option<HeaderMap>,
client_managed_handoffs: bool,
codex_responses_as_items: bool,
codex_response_item_prefix: Option<String>,
codex_response_handoff_prefix: Option<String>,
realtime_call_api_provider: Option<ApiProvider>,
session_config: RealtimeSessionConfig,
model_client: ModelClient,
@@ -296,8 +306,10 @@ impl RealtimeConversationManager {
api_provider,
architecture,
extra_headers,
client_managed_handoffs,
codex_responses_as_items,
codex_response_item_prefix,
codex_response_handoff_prefix,
realtime_call_api_provider,
session_config,
model_client,
@@ -321,8 +333,10 @@ impl RealtimeConversationManager {
let realtime_active = Arc::new(AtomicBool::new(true));
let handoff = RealtimeHandoffState::new(
handoff_output_tx,
client_managed_handoffs,
codex_responses_as_items,
codex_response_item_prefix,
codex_response_handoff_prefix,
session_kind,
);
let input_channels = RealtimeInputChannels {
@@ -479,7 +493,11 @@ impl RealtimeConversationManager {
Ok(())
}
pub(crate) async fn handoff_out(&self, output_text: String) -> CodexResult<()> {
pub(crate) async fn handoff_out(
&self,
output_text: String,
phase: Option<MessagePhase>,
) -> CodexResult<()> {
let handoff = {
let guard = self.state.lock().await;
let Some(state) = guard.as_ref() else {
@@ -490,6 +508,13 @@ impl RealtimeConversationManager {
state.handoff.clone()
};
if handoff.client_managed_handoffs {
return Ok(());
}
let response_handoff_prefix = match phase {
Some(MessagePhase::Commentary) => handoff.codex_response_handoff_prefix.clone(),
Some(MessagePhase::FinalAnswer) | None => None,
};
let active_handoff = handoff.active_handoff.lock().await.clone();
let output = match active_handoff {
Some(handoff_id) => {
@@ -502,6 +527,16 @@ impl RealtimeConversationManager {
handoff.codex_response_item_prefix.as_deref(),
),
}
} else if handoff.session_kind == RealtimeSessionKind::V1
&& handoff.codex_response_handoff_prefix.is_some()
{
RealtimeOutbound::HandoffAppend {
handoff_id,
text: realtime_backend_item(
output_text,
response_handoff_prefix.as_deref(),
),
}
} else {
RealtimeOutbound::HandoffUpdate {
handoff_id,
@@ -520,7 +555,13 @@ impl RealtimeConversationManager {
),
}
} else {
RealtimeOutbound::StandaloneHandoff { text: output_text }
RealtimeOutbound::StandaloneHandoff {
text: if handoff.session_kind == RealtimeSessionKind::V1 {
realtime_backend_item(output_text, response_handoff_prefix.as_deref())
} else {
output_text
},
}
}
}
};
@@ -565,6 +606,9 @@ impl RealtimeConversationManager {
let Some(handoff) = handoff else {
return Ok(());
};
if handoff.client_managed_handoffs {
return Ok(());
}
match handoff.session_kind {
RealtimeSessionKind::V1 => return Ok(()),
RealtimeSessionKind::V2 => {}
@@ -675,8 +719,10 @@ struct PreparedRealtimeConversationStart {
api_provider: ApiProvider,
architecture: RealtimeConversationArchitecture,
extra_headers: Option<HeaderMap>,
client_managed_handoffs: bool,
codex_responses_as_items: bool,
codex_response_item_prefix: Option<String>,
codex_response_handoff_prefix: Option<String>,
realtime_call_api_provider: Option<ApiProvider>,
requested_realtime_session_id: Option<String>,
version: RealtimeWsVersion,
@@ -744,8 +790,10 @@ async fn prepare_realtime_start(
api_provider,
architecture,
extra_headers,
client_managed_handoffs: params.client_managed_handoffs,
codex_responses_as_items: params.codex_responses_as_items,
codex_response_item_prefix: params.codex_response_item_prefix,
codex_response_handoff_prefix: params.codex_response_handoff_prefix,
realtime_call_api_provider,
requested_realtime_session_id,
version,
@@ -914,8 +962,10 @@ async fn handle_start_inner(
api_provider,
architecture,
extra_headers,
client_managed_handoffs,
codex_responses_as_items,
codex_response_item_prefix,
codex_response_handoff_prefix,
realtime_call_api_provider,
requested_realtime_session_id,
version,
@@ -931,8 +981,10 @@ async fn handle_start_inner(
api_provider,
architecture,
extra_headers,
client_managed_handoffs,
codex_responses_as_items,
codex_response_item_prefix,
codex_response_handoff_prefix,
realtime_call_api_provider,
session_config,
model_client: sess.services.model_client.clone(),
@@ -1368,6 +1420,11 @@ async fn handle_handoff_output(
.send_conversation_function_call_output(handoff_id, text)
.await
}
RealtimeOutbound::HandoffAppend { handoff_id, text } => {
writer
.send_conversation_handoff_append(handoff_id, text)
.await
}
RealtimeOutbound::ConversationItem { text } => {
writer
.send_conversation_item_create(text, ConversationTextRole::Developer)
@@ -1388,7 +1445,8 @@ async fn handle_handoff_output(
.await;
}
}
RealtimeOutbound::HandoffUpdate { handoff_id, text } => {
RealtimeOutbound::HandoffUpdate { handoff_id, text }
| RealtimeOutbound::HandoffAppend { handoff_id, text } => {
let active_handoff = handoff_state.active_handoff.lock().await.clone();
match active_handoff {
Some(active_handoff) if active_handoff == handoff_id => {}
@@ -130,8 +130,10 @@ async fn clears_active_handoff_explicitly() {
let (tx, _rx) = bounded(1);
let state = RealtimeHandoffState::new(
tx,
/*client_managed_handoffs*/ false,
/*codex_responses_as_items*/ false,
/*codex_response_item_prefix*/ None,
/*codex_response_handoff_prefix*/ None,
RealtimeSessionKind::V1,
);
+4 -2
View File
@@ -25,6 +25,7 @@ use codex_sandboxing::SandboxExecRequest;
use codex_sandboxing::SandboxType;
use codex_sandboxing::WindowsSandboxFilesystemOverrides;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use std::collections::HashMap;
#[derive(Debug)]
@@ -42,14 +43,14 @@ pub(crate) struct ExecServerEnvConfig {
#[derive(Debug)]
pub struct ExecRequest {
pub command: Vec<String>,
pub cwd: AbsolutePathBuf,
pub cwd: PathUri,
pub env: HashMap<String, String>,
pub(crate) exec_server_env_config: Option<ExecServerEnvConfig>,
pub network: Option<NetworkProxy>,
pub expiration: ExecExpiration,
pub capture_policy: ExecCapturePolicy,
pub sandbox: SandboxType,
pub windows_sandbox_policy_cwd: AbsolutePathBuf,
pub windows_sandbox_policy_cwd: PathUri,
pub windows_sandbox_workspace_roots: Vec<AbsolutePathBuf>,
pub windows_sandbox_level: WindowsSandboxLevel,
pub windows_sandbox_private_desktop: bool,
@@ -76,6 +77,7 @@ impl ExecRequest {
permission_profile: PermissionProfile,
arg0: Option<String>,
) -> Self {
let cwd = PathUri::from_abs_path(&cwd);
let windows_sandbox_policy_cwd = cwd.clone();
let (file_system_sandbox_policy, network_sandbox_policy) =
permission_profile.to_runtime_permissions();
+3 -3
View File
@@ -1134,7 +1134,7 @@ impl Session {
pub(crate) async fn route_realtime_text_input(self: &Arc<Self>, text: String) {
handlers::user_input_or_turn_inner(
self,
self.next_internal_sub_id(),
Uuid::now_v7().to_string(),
Op::UserInput {
items: vec![UserInput::Text {
text,
@@ -1809,13 +1809,13 @@ impl Session {
}
async fn maybe_mirror_event_text_to_realtime(&self, msg: &EventMsg) {
let Some(text) = realtime_text_for_event(msg) else {
let Some((text, phase)) = realtime_text_for_event(msg) else {
return;
};
if self.conversation.running_state().await.is_none() {
return;
}
if let Err(err) = self.conversation.handoff_out(text).await {
if let Err(err) = self.conversation.handoff_out(text, phase).await {
debug!("failed to mirror event text to realtime conversation: {err}");
}
}
+5 -3
View File
@@ -1664,6 +1664,7 @@ async fn resize_all_images_prepares_failures_before_history_insertion() {
)
.await;
let item = ResponseItem::FunctionCallOutput {
id: None,
call_id: "call-1".to_string(),
output: FunctionCallOutputPayload {
body: FunctionCallOutputBody::ContentItems(vec![
@@ -1689,6 +1690,7 @@ async fn resize_all_images_prepares_failures_before_history_insertion() {
.await;
let expected = vec![ResponseItem::FunctionCallOutput {
id: None,
call_id: "call-1".to_string(),
output: FunctionCallOutputPayload {
body: FunctionCallOutputBody::ContentItems(vec![
@@ -7720,7 +7722,7 @@ async fn build_initial_context_omits_default_image_save_location_with_image_hist
session
.replace_history(
vec![ResponseItem::ImageGenerationCall {
id: "ig-test".to_string(),
id: Some("ig-test".to_string()),
status: "completed".to_string(),
revised_prompt: Some("a tiny blue square".to_string()),
result: "Zm9v".to_string(),
@@ -7973,7 +7975,7 @@ async fn handle_output_item_done_records_image_save_history_message() {
);
let _ = std::fs::remove_file(&expected_saved_path);
let item = ResponseItem::ImageGenerationCall {
id: call_id.to_string(),
id: Some(call_id.to_string()),
status: "completed".to_string(),
revised_prompt: Some("a tiny blue square".to_string()),
result: "Zm9v".to_string(),
@@ -8030,7 +8032,7 @@ async fn handle_output_item_done_skips_image_save_message_when_save_fails() {
);
let _ = std::fs::remove_file(&expected_saved_path);
let item = ResponseItem::ImageGenerationCall {
id: call_id.to_string(),
id: Some(call_id.to_string()),
status: "completed".to_string(),
revised_prompt: Some("broken payload".to_string()),
result: "_-8".to_string(),
+3 -3
View File
@@ -1460,11 +1460,11 @@ fn agent_message_text(item: &codex_protocol::items::AgentMessageItem) -> String
.collect()
}
pub(super) fn realtime_text_for_event(msg: &EventMsg) -> Option<String> {
pub(super) fn realtime_text_for_event(msg: &EventMsg) -> Option<(String, Option<MessagePhase>)> {
match msg {
EventMsg::AgentMessage(event) => Some(event.message.clone()),
EventMsg::AgentMessage(event) => Some((event.message.clone(), event.phase.clone())),
EventMsg::ItemCompleted(event) => match &event.item {
TurnItem::AgentMessage(item) => Some(agent_message_text(item)),
TurnItem::AgentMessage(item) => Some((agent_message_text(item), item.phase.clone())),
_ => None,
},
EventMsg::Error(_)
+4
View File
@@ -624,6 +624,7 @@ pub(crate) fn response_input_to_response_item(input: &ResponseInputItem) -> Opti
match input {
ResponseInputItem::FunctionCallOutput { call_id, output } => {
Some(ResponseItem::FunctionCallOutput {
id: None,
call_id: call_id.clone(),
output: output.clone(),
metadata: None,
@@ -634,6 +635,7 @@ pub(crate) fn response_input_to_response_item(input: &ResponseInputItem) -> Opti
name,
output,
} => Some(ResponseItem::CustomToolCallOutput {
id: None,
call_id: call_id.clone(),
name: name.clone(),
output: output.clone(),
@@ -642,6 +644,7 @@ pub(crate) fn response_input_to_response_item(input: &ResponseInputItem) -> Opti
ResponseInputItem::McpToolCallOutput { call_id, output } => {
let output = output.as_function_call_output_payload();
Some(ResponseItem::FunctionCallOutput {
id: None,
call_id: call_id.clone(),
output,
metadata: None,
@@ -653,6 +656,7 @@ pub(crate) fn response_input_to_response_item(input: &ResponseInputItem) -> Opti
execution,
tools,
} => Some(ResponseItem::ToolSearchOutput {
id: None,
call_id: Some(call_id.clone()),
status: status.clone(),
execution: execution.clone(),
@@ -64,6 +64,7 @@ fn external_context_pollution_items_include_web_search_and_tool_search() {
metadata: None,
},
ResponseItem::ToolSearchOutput {
id: None,
call_id: Some("search-1".to_string()),
status: "completed".to_string(),
execution: "client".to_string(),
@@ -104,6 +105,7 @@ fn external_context_pollution_items_exclude_local_tool_calls() {
metadata: None,
},
ResponseItem::FunctionCallOutput {
id: None,
call_id: "call-1".to_string(),
output: FunctionCallOutputPayload::from_text("ok".to_string()),
metadata: None,
@@ -117,6 +119,7 @@ fn external_context_pollution_items_exclude_local_tool_calls() {
metadata: None,
},
ResponseItem::CustomToolCallOutput {
id: None,
call_id: "custom-1".to_string(),
name: Some("apply_patch".to_string()),
output: FunctionCallOutputPayload::from_text("ok".to_string()),
@@ -418,7 +421,7 @@ fn completed_item_keeps_mailbox_delivery_open_for_commentary_messages() {
#[test]
fn completed_item_defers_mailbox_delivery_for_image_generation_calls() {
let item = ResponseItem::ImageGenerationCall {
id: "ig-1".to_string(),
id: Some("ig-1".to_string()),
status: "completed".to_string(),
revised_prompt: None,
result: "Zm9v".to_string(),
+2 -2
View File
@@ -199,7 +199,7 @@ pub(crate) async fn execute_user_shell_command(
let permission_profile = PermissionProfile::Disabled;
let exec_env = ExecRequest {
command: exec_command.clone(),
cwd: cwd.clone(),
cwd: cwd.clone().into(),
env: exec_env_map,
exec_server_env_config: None,
// `/shell` is the explicit full-access escape hatch, so it must not
@@ -210,7 +210,7 @@ pub(crate) async fn execute_user_shell_command(
expiration: USER_SHELL_TIMEOUT_MS.into(),
capture_policy: ExecCapturePolicy::ShellTool,
sandbox: SandboxType::None,
windows_sandbox_policy_cwd: cwd.clone(),
windows_sandbox_policy_cwd: cwd.clone().into(),
windows_sandbox_workspace_roots: turn_context.config.effective_workspace_roots(),
windows_sandbox_level: turn_context.windows_sandbox_level,
windows_sandbox_private_desktop: turn_context
+1 -1
View File
@@ -76,7 +76,7 @@ fn truncates_before_requested_user_message() {
user_msg("u2"),
assistant_msg("a3"),
ResponseItem::Reasoning {
id: "r1".to_string(),
id: Some("r1".to_string()),
summary: vec![ReasoningItemReasoningSummary::SummaryText {
text: "s".to_string(),
}],
@@ -73,7 +73,7 @@ fn truncates_rollout_from_start_before_nth_user_only() {
user_msg("u2"),
assistant_msg("a3"),
ResponseItem::Reasoning {
id: "r1".to_string(),
id: Some("r1".to_string()),
summary: vec![ReasoningItemReasoningSummary::SummaryText {
text: "s".to_string(),
}],
@@ -299,6 +299,7 @@ impl CoreTurnHost {
self.exec
.session
.inject_if_running(vec![ResponseItem::CustomToolCallOutput {
id: None,
call_id,
name: Some(PUBLIC_TOOL_NAME.to_string()),
output: FunctionCallOutputPayload::from_text(text),
+8 -3
View File
@@ -21,6 +21,7 @@ use codex_protocol::protocol::PatchApplyStatus;
use codex_protocol::protocol::TurnDiffEvent;
use codex_shell_command::parse_command::parse_command;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use std::collections::HashMap;
use std::path::PathBuf;
use std::time::Duration;
@@ -133,7 +134,7 @@ pub(crate) enum ToolEmitter {
},
UnifiedExec {
command: Vec<String>,
cwd: AbsolutePathBuf,
cwd: PathUri,
source: ExecCommandSource,
parsed_cmd: Vec<ParsedCommand>,
process_id: Option<String>,
@@ -165,7 +166,7 @@ impl ToolEmitter {
pub fn unified_exec(
command: &[String],
cwd: AbsolutePathBuf,
cwd: PathUri,
source: ExecCommandSource,
process_id: Option<String>,
) -> Self {
@@ -320,11 +321,15 @@ impl ToolEmitter {
},
stage,
) => {
// TODO(anp): Migrate exec command protocol events to PathUri.
let Ok(cwd) = cwd.to_abs_path() else {
return;
};
emit_exec_stage(
ctx,
ExecCommandInput::new(
command,
cwd,
&cwd,
parsed_cmd,
*source,
/*interaction_input*/ None,
@@ -205,16 +205,19 @@ fn format_update_chunks_for_progress(chunks: &[codex_apply_patch::UpdateFileChun
fn file_paths_for_action(action: &ApplyPatchAction) -> Vec<AbsolutePathBuf> {
let mut keys = Vec::new();
let cwd = &action.cwd;
// TODO(anp): Migrate permission path accounting to PathUri.
let Ok(cwd) = action.cwd.to_abs_path() else {
return keys;
};
for (path, change) in action.changes() {
if let Some(key) = to_abs_path(cwd, path) {
if let Some(key) = to_abs_path(&cwd, path) {
keys.push(key);
}
if let ApplyPatchFileChange::Update { move_path, .. } = change
&& let Some(dest) = move_path
&& let Some(key) = to_abs_path(cwd, dest)
&& let Some(key) = to_abs_path(&cwd, dest)
{
keys.push(key);
}
@@ -20,6 +20,7 @@ use codex_tools::ToolSpec;
use codex_tools::coalesce_loadable_tool_specs;
use std::sync::Arc;
use std::sync::Mutex;
use tracing::instrument;
pub struct ToolSearchHandler {
search_infos: Vec<ToolSearchInfo>,
@@ -33,6 +34,7 @@ pub(crate) struct ToolSearchHandlerCache {
}
impl ToolSearchHandlerCache {
#[instrument(level = "trace", skip_all, fields(search_info_count = search_infos.len()))]
pub(crate) fn get_or_build(&self, search_infos: Vec<ToolSearchInfo>) -> Arc<ToolSearchHandler> {
{
let cached = self.cached();
@@ -64,6 +66,11 @@ impl ToolSearchHandlerCache {
}
impl ToolSearchHandler {
#[instrument(
level = "trace",
skip_all,
fields(search_info_count = search_infos.len())
)]
pub(crate) fn new(search_infos: Vec<ToolSearchInfo>) -> Self {
let search_source_infos = search_infos
.iter()
@@ -28,9 +28,13 @@ use crate::unified_exec::generate_chunk_id;
use codex_features::Feature;
use codex_otel::SessionTelemetry;
use codex_otel::TOOL_CALL_UNIFIED_EXEC_METRIC;
use codex_sandboxing::SandboxManager;
use codex_sandboxing::SandboxType;
use codex_sandboxing::SandboxablePreference;
use codex_tools::ToolName;
use codex_tools::ToolSpec;
use codex_utils_output_truncation::approx_token_count;
use codex_utils_path_uri::PathConvention;
use super::super::shell_spec::CommandToolOptions;
use super::super::shell_spec::create_exec_command_tool_with_environment_id;
@@ -129,33 +133,68 @@ impl ExecCommandHandler {
"unified exec is unavailable in this session".to_string(),
));
};
// TODO(anp): Resolve tool paths using the selected environment's native path convention
// so unified exec can support relative paths in foreign environments.
let native_environment_cwd = turn_environment.cwd().to_abs_path().map_err(|err| {
FunctionCallError::RespondToModel(format!(
"environment cwd `{}` is not native to the Codex host: {err}",
turn_environment.cwd()
))
})?;
let native_environment_cwd = turn_environment.cwd().clone();
let cwd = environment_args
.workdir
.as_deref()
.filter(|workdir| !workdir.is_empty())
.map_or_else(
|| native_environment_cwd.clone(),
|| Ok(native_environment_cwd.clone()),
|workdir| native_environment_cwd.join(workdir),
);
)
.map_err(|err| FunctionCallError::RespondToModel(err.to_string()))?;
let environment = Arc::clone(&turn_environment.environment);
let fs = environment.get_filesystem();
let args: ExecCommandArgs = parse_arguments_with_base_path(&arguments, &cwd)?;
// A foreign cwd cannot seed the AbsolutePathBufGuard used to resolve relative paths in the
// permissions config below. Consult the configured platform-sandbox requirement before
// deciding whether parsing may continue without that base path.
let sandbox = SandboxManager::new().select_initial(
&turn.file_system_sandbox_policy(),
turn.network_sandbox_policy(),
SandboxablePreference::Auto,
turn.windows_sandbox_level,
turn.network.is_some(),
);
// `to_abs_path()` alone cannot identify foreign drive paths: `file:///C:/repo` is
// representable as `/C:/repo` on POSIX. Require the inferred convention to match too.
let cwd_uses_native_convention =
cwd.infer_path_convention() == Some(PathConvention::native());
// TODO(anp): Remove this parsing split once sandboxing supports foreign paths.
let native_cwd = match cwd.to_abs_path() {
Ok(cwd) if cwd_uses_native_convention => Some(cwd),
_ if sandbox == SandboxType::None => None,
Err(err) => return Err(FunctionCallError::RespondToModel(err.to_string())),
Ok(_) => {
return Err(FunctionCallError::RespondToModel(format!(
"path URI `{cwd}` does not use the host's native {} path convention",
PathConvention::native()
)));
}
};
let args: ExecCommandArgs = match native_cwd.as_ref() {
Some(native_cwd) => {
// The base path only resolves paths nested in the permissions config types.
parse_arguments_with_base_path(&arguments, native_cwd)?
}
None => {
// Parsing without a base only skips relative-path resolution inside the
// permissions config. That is safe only for a truly unsandboxed attempt;
// sandboxed attempts fall through and return the conversion error below.
parse_arguments(&arguments)?
}
};
let hook_command = args.cmd.clone();
maybe_emit_implicit_skill_invocation(
session.as_ref(),
context.turn.as_ref(),
&hook_command,
&cwd,
)
.await;
// TODO(anp) wire PathUri through implicit skills instead of skipping on foreign paths
if let Some(native_cwd) = native_cwd.as_ref() {
maybe_emit_implicit_skill_invocation(
session.as_ref(),
context.turn.as_ref(),
&hook_command,
native_cwd,
)
.await;
}
let process_id = manager.allocate_process_id().await;
let shell_mode =
shell_mode_for_environment(&turn.unified_exec_shell_mode, environment.as_ref());
@@ -191,10 +230,12 @@ impl ExecCommandHandler {
let exec_permission_approvals_enabled =
session.features().enabled(Feature::ExecPermissionApprovals);
let requested_additional_permissions = additional_permissions.clone();
// TODO(anp): Make permission matching operate on PathUri for remote environments.
let permission_cwd = native_cwd.as_ref().unwrap_or(&turn.config.cwd);
let effective_additional_permissions = apply_granted_turn_permissions(
context.session.as_ref(),
&turn_environment.environment_id,
cwd.as_path(),
permission_cwd.as_path(),
sandbox_permissions,
additional_permissions,
)
@@ -234,7 +275,7 @@ impl ExecCommandHandler {
effective_additional_permissions.sandbox_permissions,
effective_additional_permissions.additional_permissions,
effective_additional_permissions.permissions_preapproved,
&cwd,
permission_cwd,
)
},
|permissions| Ok(Some(permissions)),
@@ -246,18 +287,20 @@ impl ExecCommandHandler {
}
};
if let Some(output) = intercept_apply_patch(
&command,
&cwd,
fs.as_ref(),
turn_environment.clone(),
context.session.clone(),
context.turn.clone(),
Some(&tracker),
&context.call_id,
"exec_command",
)
.await?
// TODO(anp) intercept apply_patch properly when cwd is a foreign path
if let Some(native_cwd) = native_cwd.as_ref()
&& let Some(output) = intercept_apply_patch(
&command,
native_cwd,
fs.as_ref(),
turn_environment.clone(),
context.session.clone(),
context.turn.clone(),
Some(&tracker),
&context.call_id,
"exec_command",
)
.await?
{
manager.release_process_id(process_id).await;
return Ok(boxed_tool_output(ExecCommandToolOutput {
+4 -2
View File
@@ -239,8 +239,10 @@ impl ToolOrchestrator {
// Platform-specific flag gating is handled by SandboxManager::select_initial.
let use_legacy_landlock = turn_ctx.config.features.use_legacy_landlock();
#[allow(deprecated)]
let sandbox_cwd = tool.sandbox_cwd(req).unwrap_or(&turn_ctx.cwd);
let sandbox_policy_cwd = PathUri::from_abs_path(sandbox_cwd);
let sandbox_policy_cwd = tool
.sandbox_cwd(req)
.cloned()
.unwrap_or_else(|| PathUri::from_abs_path(&turn_ctx.cwd));
let workspace_roots = turn_ctx.config.effective_workspace_roots();
let initial_attempt = SandboxAttempt {
sandbox: initial_sandbox,

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